export { AgentOpsError, type AgentOpsErrorOptions } from "./client-http.js";

export type TokenProvider = string | (() => string | Promise<string>);

export interface AgentOpsClientOptions {
  /** Full existing API base, for example https://api.example.com/api/saas/ops. */
  baseUrl: string;
  organizationId: string;
  /** Existing product-user bearer token. Called again for every request. */
  token: TokenProvider;
  fetch?: typeof globalThis.fetch;
  /** Per-request timeout including token lookup and reading the response. Default 30000. */
  timeoutMs?: number;
}

export interface RequestOptions {
  signal?: AbortSignal;
}

export interface WaitOptions extends RequestOptions {
  /** Overall local wait timeout. Default 300000. Does not cancel the server task. */
  timeoutMs?: number;
  /** Delay between detail GET requests. Default 1000. */
  pollIntervalMs?: number;
}

export interface Profile {
  organization_id: string;
  configured: boolean;
  revision: number;
  display_name?: string | null;
  provider?: string | null;
  unit_id?: string | null;
  service_id?: string | null;
  desired_config_sha256?: string | null;
  product_code?: string;
}

export interface Connection {
  organization_id: string;
  can_run: boolean;
  reason?: string | null;
  checked_at: string;
  observed_at?: string | null;
  infrastructure: { state?: string };
  runtime: { state?: string };
  provider: { state?: string; inference_verified?: boolean };
}

export type TaskStatus =
  | "pending" | "queued" | "claimed" | "running" | "dispatching"
  | "completed" | "failed" | "canceled" | "cancelled"
  | "needs_input" | "pending_approval" | "blocked" | "dispatch_uncertain"
  | (string & {});

/** Device fields for selecting a task target from the organization's visible fleet. */
export interface HubDevice {
  id: string;
  hostname: string;
  execution_status: string;
  /** PC registry profile UUID used by devices.getProfileConnection(), when supplied by the Hub. */
  profile_id?: string;
  /** Manifest hash expected by the Hub when dispatching a task. */
  profile_sha256: string | null;
  /** Hub's readiness and permission check at the time of this snapshot. */
  can_send_task: boolean;
}

export interface HubDeviceList {
  organization_id: string;
  checked_at: string;
  hosts: HubDevice[];
}

export interface HubProfileDevice {
  host_uuid: string;
  hostname: string;
  /** Device-specific deployment version, for example cfg-v2. */
  expected_profile_version: string | null;
  expected_profile_sha256: string | null;
  /** The Hub verified that the device materialized the manifest for the current selected binding. */
  materialized: boolean;
  binding_current: boolean;
  profile_update_pending: boolean;
  enrollment_status: string;
  /** Last accepted heartbeat matching the manifest and runtime bundle. It may be stale. */
  heartbeat_at: string | null;
  runtime_state: string;
}

export interface HubProfileConnection {
  organization_id: string;
  checked_at: string;
  selected: {
    profile_uuid: string;
    /** Registry record revision, distinct from the device deployment version and workspace revision. */
    profile_revision: number;
    record_sha256: string;
  };
  devices: HubProfileDevice[];
}

export interface TaskQuestion {
  question_id: string;
  question: string;
  context?: unknown;
}

export interface AnswerReceipt {
  client_request_id: string;
  question_id: string;
  status: string;
}

export interface Task {
  organization_id: string;
  /** Product task UUID. Use this value for get, wait, watch and answer. */
  id: string;
  /** Original task-creation request UUID, also in an answer response. */
  client_request_id: string;
  /** Internal runtime identifier; not the input to tasks.get(). */
  task_id: string;
  status: TaskStatus;
  prompt: string;
  result: string | null;
  question: TaskQuestion | null;
  answer_receipt: AnswerReceipt | null;
  error_code?: string | null;
  pc_host_id?: string | null;
  pc_profile_sha256?: string | null;
  created_at: string;
  updated_at: string;
}

export interface TaskList {
  organization_id: string;
  /** Current API returns the latest 50 stored snapshots, without pagination. */
  items: Task[];
}

export type CreateTaskInput = {
  prompt: string;
  profileRevision: number;
  /** Create once and retain for every retry of the same logical request. */
  clientRequestId: string;
} & (
  | { pcHostId?: never; pcProfileSha256?: never }
  | { pcHostId: string; pcProfileSha256: string }
);

export interface AnswerTaskInput {
  questionId: string;
  answer: string;
  /** Answer request UUID, separate from the original task-creation UUID. */
  clientRequestId: string;
}

export class AgentOpsClient {
  constructor(options: AgentOpsClientOptions);
  readonly profile: {
    get(options?: RequestOptions): Promise<Profile>;
  };
  readonly connection: {
    get(options?: RequestOptions): Promise<Connection>;
  };
  readonly devices: {
    list(options?: RequestOptions): Promise<HubDeviceList>;
    /** Read the selected PC registry profile and its visible devices' application evidence. */
    getProfileConnection(profileId: string, options?: RequestOptions): Promise<HubProfileConnection>;
  };
  readonly tasks: {
    list(options?: RequestOptions): Promise<TaskList>;
    get(taskId: string, options?: RequestOptions): Promise<Task>;
    create(input: CreateTaskInput, options?: RequestOptions): Promise<Task>;
    answer(taskId: string, input: AnswerTaskInput, options?: RequestOptions): Promise<Task>;
    /** Returns on completion, failure, input or approval required, blocking or uncertain dispatch. */
    wait(taskId: string, options?: WaitOptions): Promise<Task>;
    /** Yields the first snapshot and subsequent content changes (excluding updated_at-only refreshes), until wait() would return. */
    watch(taskId: string, options?: WaitOptions): AsyncIterableIterator<Task>;
  };
}
