import type { LiveBuildsPayload } from "./live-builds";
export type { LiveBuildBuild, LiveBuildCommit, LiveBuildImage, LiveBuildRecord, LiveBuildsPayload } from "./live-builds";

export type Tone = "ok" | "source" | "pending" | "blocked" | "error" | "warn" | "dev-live" | "dry-run";
export type RouteId = "workspace" | "performance" | "skills" | "management" | "access" | "gate" | "help" | "settings";
export type AuthState = "checking" | "login" | "authenticated";
export type ProviderProfile = string;

export interface AuthUser {
  id?: string;
  username?: string;
  displayName?: string;
  name?: string;
  role?: AccessUserRole;
  status?: AccessUserStatus;
}

export interface AuthSession {
  authenticated: boolean;
  mode: "server";
  user?: AuthUser;
  actor?: AuthUser;
  expiresAt?: string | null;
}

export interface ApiResult<T> {
  ok: boolean;
  status: number;
  data: T | null;
  error: string | null;
}

export interface LiveProbePayload {
  status?: string;
  serviceId?: string;
  commitId?: string;
  revision?: string;
  runtime?: Record<string, unknown>;
  codeAgent?: CodeAgentAvailability;
  availability?: CodeAgentAvailability;
  [key: string]: unknown;
}

export interface LiveSurface {
  healthLive: ApiResult<LiveProbePayload>;
  health: ApiResult<LiveProbePayload>;
  restIndex: ApiResult<LiveProbePayload>;
  adapter: ApiResult<LiveProbePayload>;
  hwpodSpecs: ApiResult<HwpodSpecsResponse>;
  hwpodNodeOps: ApiResult<HwpodNodeOpsResponse>;
  liveBuilds: ApiResult<LiveBuildsPayload>;
  loadedAt: string;
}

export interface WebPerformanceSummaryRow {
  kind?: string;
  metric?: string;
  route?: string;
  method?: string;
  statusClass?: string;
  outcome?: string;
  count?: number;
  average?: number;
  p50?: number;
  p95?: number;
  unit?: "seconds" | "score";
  tone?: Tone | string;
  problem?: string;
}

export interface WebPerformanceSummaryResponse {
  serviceId?: string;
  route?: string;
  source?: string;
  observedAt?: string;
  namespace?: string;
  gitopsTarget?: string;
  summary?: {
    sampleCount?: number;
    sampleSeries?: number;
    durationSeries?: number;
    clsSeries?: number;
    routeCount?: number;
    problemCount?: number;
    status?: string;
  };
  apiRoutes?: WebPerformanceSummaryRow[];
  webVitals?: WebPerformanceSummaryRow[];
  longTasks?: WebPerformanceSummaryRow[];
  problems?: WebPerformanceSummaryRow[];
  rows?: WebPerformanceSummaryRow[];
}

export interface CodeAgentAvailability {
  status?: string;
  ready?: boolean;
  provider?: string;
  mode?: string;
  backend?: string;
  capabilityLevel?: string;
  sessionMode?: string;
  implementationType?: string;
  runner?: Record<string, unknown>;
  session?: Record<string, unknown>;
  longLivedSessionGate?: Record<string, unknown>;
  providerTrace?: Record<string, unknown>;
  blockers?: Array<{ code?: string; message?: string }>;
  [key: string]: unknown;
}

export interface WorkspaceRecord {
  workspaceId: string;
  projectId?: string | null;
  revision?: number;
  updatedAt?: string;
  selectedConversationId?: string | null;
  selectedAgentSessionId?: string | null;
  activeTraceId?: string | null;
  workspace?: {
    projectId?: string | null;
    selectedConversationId?: string | null;
    selectedAgentSessionId?: string | null;
    threadId?: string | null;
    sessionStatus?: string | null;
    messages?: ChatMessage[];
    updatedAt?: string;
    [key: string]: unknown;
  };
  selectedConversation?: ConversationRecord | null;
}

export interface ConversationRecord {
  conversationId: string;
  projectId?: string | null;
  sessionId?: string | null;
  threadId?: string | null;
  status?: string | null;
  updatedAt?: string | null;
  startedAt?: string | null;
  lastTraceId?: string | null;
  messageCount?: number;
  firstUserMessagePreview?: string | null;
  title?: string | null;
  name?: string | null;
  snapshot?: {
    title?: string | null;
    sessionStatus?: string | null;
    updatedAt?: string | null;
    firstUserMessagePreview?: string | null;
    source?: string | null;
  };
  session?: {
    sessionId?: string | null;
    threadId?: string | null;
  };
  messages?: ChatMessage[];
}

export type ChatRole = "user" | "agent" | "system";
export type ChatStatus = "source" | "sent" | "running" | "completed" | "failed" | "blocked" | "timeout" | "canceled";

export interface TraceEvent {
  ts?: string;
  kind?: string;
  type?: string;
  status?: string;
  message?: string;
  itemId?: string;
  toolName?: string;
  command?: string;
  exitCode?: number;
  stdoutSummary?: string;
  stderrSummary?: string;
  elapsedMs?: number;
  [key: string]: unknown;
}

export interface RunnerTrace {
  traceId?: string;
  status?: string;
  sessionId?: string;
  threadId?: string;
  runnerKind?: string;
  sessionMode?: string;
  events?: TraceEvent[];
  eventCount?: number;
  eventsCompacted?: boolean;
  fullTraceLoaded?: boolean;
  [key: string]: unknown;
}

export interface ChatMessage {
  id: string;
  role: ChatRole;
  title: string;
  text: string;
  status: ChatStatus;
  createdAt: string;
  updatedAt?: string;
  traceId?: string | null;
  conversationId?: string | null;
  sessionId?: string | null;
  threadId?: string | null;
  retryOf?: string | null;
  retryInput?: string | null;
  traceReplayStatus?: string | null;
  runnerTrace?: RunnerTrace | null;
  traceEvents?: TraceEvent[];
  error?: {
    code?: string;
    message?: string;
    category?: string;
    providerStatus?: number;
    [key: string]: unknown;
  } | null;
  [key: string]: unknown;
}

export interface AgentChatResponse {
  status?: string;
  reply?: string;
  text?: string;
  summary?: string;
  traceId?: string;
  conversationId?: string;
  sessionId?: string;
  threadId?: string;
  workspaceId?: string;
  workspaceRevision?: number;
  sessionStatus?: string;
  availability?: CodeAgentAvailability;
  runnerTrace?: RunnerTrace;
  traceEvents?: TraceEvent[];
  assistantText?: string;
  agentRun?: AgentRunProvenance;
  resultUrl?: string;
  traceUrl?: string;
  accepted?: boolean;
  shortConnection?: boolean;
  fullBodyAvailable?: boolean;
  error?: string | { code?: string; message?: string; providerStatus?: number; [key: string]: unknown };
  [key: string]: unknown;
}

export interface AgentChatReply {
  messageId?: string;
  role?: "assistant" | "user" | "system";
  content?: string;
  createdAt?: string;
  [key: string]: unknown;
}

export interface AgentRunProvenance {
  adapter?: string;
  runId?: string;
  commandId?: string;
  attemptId?: string;
  runnerId?: string;
  jobName?: string;
  namespace?: string;
  backendProfile?: string;
  status?: string;
  runStatus?: string;
  commandState?: string;
  terminalStatus?: string;
  reuseEligible?: boolean;
  valuesPrinted?: boolean;
  [key: string]: unknown;
}

export interface ProviderProfileSecretRef {
  namespace?: string;
  name?: string;
  keys?: string[];
  mountPath?: string;
}

export interface ProviderProfileBridgeSummary {
  kind?: string;
  route?: string;
  serviceUrl?: string;
  responsesPath?: string;
  forbiddenHosts?: string[];
  valuesPrinted?: boolean;
}

export interface ProviderProfileStatusItem {
  profile: ProviderProfile;
  backendProfile?: string;
  backendKind?: string;
  configured?: boolean;
  failureKind?: string | null;
  secretRef?: ProviderProfileSecretRef;
  resourceVersion?: string | null;
  credentialHashSuffix?: string | null;
  configHashSuffix?: string | null;
  updatedAt?: string | null;
  keyPresence?: Record<string, boolean>;
  lastValidation?: ProviderProfileValidation | null;
  bridge?: ProviderProfileBridgeSummary;
  valuesPrinted?: boolean;
  [key: string]: unknown;
}

export interface ProviderProfileDelegationSummary {
  provider?: string;
  requestId?: string;
  agentRunBaseUrl?: string;
  agentRunHost?: string;
  traceId?: string;
  httpStatus?: number;
  elapsedMs?: number;
  valuesPrinted?: boolean;
}

export interface ProviderProfilesResponse {
  ok?: boolean;
  status?: string;
  contractVersion?: string;
  actor?: AuthUser | null;
  profile?: ProviderProfile;
  items?: ProviderProfileStatusItem[];
  count?: number;
  data?: ProviderProfileStatusItem | ProviderProfilesData | ProviderProfileValidation | ProviderProfileConfig | null;
  delegation?: ProviderProfileDelegationSummary;
  error?: { code?: string; message?: string; failureKind?: string; [key: string]: unknown };
  valuesPrinted?: boolean;
}

export interface ProviderProfileConfig extends ProviderProfileStatusItem {
  configToml?: string;
  configTomlPrinted?: boolean;
  credentialValuesPrinted?: boolean;
}

export interface ProviderProfilesData {
  items?: ProviderProfileStatusItem[];
  count?: number;
  valuesPrinted?: boolean;
}

export interface ProviderProfileValidation {
  validationId?: string;
  profile?: ProviderProfile;
  runId?: string;
  commandId?: string;
  status?: string;
  result?: {
    status?: string;
    terminalStatus?: string;
    failureKind?: string | null;
    assistantText?: string;
    agentRun?: AgentRunProvenance;
    [key: string]: unknown;
  };
  runnerJobs?: Array<{ jobName?: string; status?: string; terminalStatus?: string; [key: string]: unknown }>;
  lastSeq?: number;
  valuesPrinted?: boolean;
  bridge?: ProviderProfileBridgeSummary;
  [key: string]: unknown;
}

export interface AgentChatResultResponse {
  status?: string;
  traceId?: string;
  conversationId?: string;
  sessionId?: string | null;
  threadId?: string | null;
  accepted?: boolean;
  shortConnection?: boolean;
  assistantText?: string;
  reply?: AgentChatReply | string;
  agentRun?: AgentRunProvenance;
  runnerTrace?: RunnerTrace;
  traceEvents?: TraceEvent[];
  availability?: CodeAgentAvailability;
  fullBodyAvailable?: boolean;
  error?: string | { code?: string; message?: string; providerStatus?: number; [key: string]: unknown };
  [key: string]: unknown;
}

export interface SessionTab {
  key: string;
  label: string;
  subtitle: string;
  projectId?: string | null;
  conversationId?: string | null;
  sessionId?: string | null;
  threadId?: string | null;
  lastTraceId?: string | null;
  status: string;
  messageCount: number;
  active: boolean;
  updatedAt?: string | null;
  userPreview?: string | null;
}

export interface HwpodNodeOpsResult {
  opId?: string;
  op?: string;
  ok?: boolean;
  status?: string;
  output?: Record<string, unknown>;
  blocker?: { code?: string; layer?: string; summary?: string; userMessage?: string; retryable?: boolean; [key: string]: unknown };
  [key: string]: unknown;
}

export interface HwpodNodeOpsResponse {
  ok?: boolean;
  status?: string;
  contractVersion?: string;
  route?: string;
  serviceId?: string;
  apiRole?: string;
  nodeRole?: string;
  planId?: string;
  hwpodId?: string;
  nodeId?: string;
  acceptedOps?: number;
  supportedOps?: string[];
  results?: HwpodNodeOpsResult[];
  blocker?: { code?: string; layer?: string; summary?: string; userMessage?: string; retryable?: boolean; [key: string]: unknown } | null;
  requestMeta?: Record<string, unknown>;
  observedAt?: string;
  [key: string]: unknown;
}

export interface HwpodSpecsResponse {
  ok?: boolean;
  status?: string;
  contractVersion?: string;
  route?: string;
  count?: number;
  availableCount?: number | null;
  specs?: HwpodSpecDiscoveryItem[];
  observedAt?: string;
  [key: string]: unknown;
}

export interface HwpodSpecDiscoveryItem {
  ok?: boolean;
  status?: string;
  name?: string;
  hwpodId?: string;
  uid?: string | null;
  specPath?: string;
  source?: Record<string, unknown>;
  nodeId?: string;
  nodeType?: string | null;
  workspacePath?: string;
  workspace?: Record<string, unknown>;
  targetDevice?: Record<string, unknown>;
  availability?: { ok?: boolean | null; status?: string; checkedAt?: string | null; results?: HwpodNodeOpsResult[]; blocker?: Record<string, unknown> | null; [key: string]: unknown };
  [key: string]: unknown;
}

export type AccessUserRole = "admin" | "user";
export type AccessUserStatus = "active" | "disabled";
export type AccessToolId = "hwpod" | "unidesk_ssh" | "trans_cmd" | "github_pr";

export interface OpenFgaStatus {
  contractVersion?: string;
  mode?: "off" | "shadow" | "enforce" | string;
  configured?: boolean;
  ready?: boolean;
  degraded?: boolean;
  storeId?: string | null;
  modelId?: string | null;
  tupleCount?: number;
  error?: string;
  [key: string]: unknown;
}

export interface AdminAccessTuple {
  userId?: string;
  relation?: string;
  object?: string;
  createdByAdminId?: string;
  createdAt?: string;
}

export interface AdminAccessUserSummary {
  user: AuthUser;
  tupleCount?: number;
  tools?: Partial<Record<AccessToolId, boolean>>;
}

export interface AdminAccessMatrixResponse {
  contractVersion?: string;
  actor?: AuthUser | null;
  user: AuthUser;
  openfga?: OpenFgaStatus;
  tools: Record<AccessToolId, boolean>;
  tuples?: AdminAccessTuple[];
}

export interface AdminAccessSummaryResponse {
  contractVersion?: string;
  actor?: AuthUser | null;
  openfga?: OpenFgaStatus;
  counts?: { users?: number; tuples?: number; toolTuples?: number; [key: string]: unknown };
  supported?: { toolIds?: AccessToolId[]; [key: string]: unknown };
}

export interface AdminAccessUsersResponse {
  contractVersion?: string;
  actor?: AuthUser | null;
  openfga?: OpenFgaStatus;
  users?: AdminAccessUserSummary[];
  count?: number;
}

export interface AdminAccessMutationResponse {
  ok?: boolean;
  changed?: boolean;
  updated?: boolean;
  access?: AdminAccessMatrixResponse | null;
  result?: Record<string, unknown>;
  user?: AuthUser;
}

export interface SkillRef {
  name: string;
  required?: boolean;
  injectStages?: string[];
  path?: string;
  [key: string]: unknown;
}

export interface SkillItem {
  id: string;
  name?: string;
  title?: string;
  status?: string;
  description?: string;
  path?: string;
  [key: string]: unknown;
}

export interface SkillsResponse {
  skills?: SkillItem[];
  roots?: Record<string, unknown> | null;
  agentRunAssembly?: {
    status?: string;
    counts?: Record<string, number>;
    skillRefs?: SkillRef[];
    toolAliases?: SkillRef[];
    promptRefs?: SkillRef[];
    promptAssembly?: { refs?: SkillRef[]; status?: string; count?: number; requiredCount?: number; injectStages?: string[] };
    resourceBundle?: { skillsDir?: string; commitId?: string };
  } | null;
}

export interface SkillTreeResponse {
  files?: Array<{ path: string; type?: string; sizeBytes?: number }>;
  tree?: Array<{ path: string; type?: string; sizeBytes?: number }>;
}

export interface SkillFileResponse {
  file?: { path: string; content?: string; status?: string };
}
