import type {
  CopyOptimizationRequest,
  CopyOptimizationResult,
  OptimizedArticle,
  QaReport,
} from "../domain/types";
import type { LlmAuditSummary } from "../llm/audit";

export type OptimizationCaseType = "article" | "human_copy";
export type OptimizationCaseStatus =
  | "running"
  | "optimized"
  | "failed"
  | "archived";
export type ResultVersionStatus = "optimized" | "failed";

export interface ProcessSummaryStep {
  stage: string;
  started_at: string;
  ended_at: string;
  duration_ms: number;
  status: "success" | "failed";
  error_summary?: string;
  rewrite_round?: number;
  produced_result_version: boolean;
}

export interface OptimizationCase {
  id: string;
  case_type: OptimizationCaseType;
  title: string;
  summary: string;
  status: OptimizationCaseStatus;
  customer_name: string;
  brand_name: string;
  project_tags: string[];
  notes: string;
  publish_target: string;
  source_excerpt: string;
  result_excerpt: string;
  latest_result_version_id: string | null;
  latest_version_number: number | null;
  last_error_stage: string | null;
  last_error_summary: string | null;
  archived_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface CaseInput {
  case_id: string;
  case_type: OptimizationCaseType;
  article_job_id: string | null;
  payload: ArticleCaseInputPayload | HumanCopyCaseInputPayload;
  created_at: string;
  updated_at: string;
}

export interface ArticleCaseInputPayload {
  source_title: string;
  source_body: string;
  image_inputs: Array<{ type: "description" | "link"; content: string }>;
  publish_platform: string;
  user_instructions: string;
  fact_card?: unknown;
}

export type HumanCopyCaseInputPayload = CopyOptimizationRequest;

export interface ArticleResultVersionPayload {
  article: OptimizedArticle;
  qa_report: QaReport;
  export_paths: Record<string, string>;
}

export type HumanCopyResultVersionPayload = CopyOptimizationResult;

export interface OptimizationResultVersion {
  id: string;
  case_id: string;
  case_type: OptimizationCaseType;
  version: number;
  status: ResultVersionStatus;
  article_job_id: string | null;
  article_revision: number | null;
  result_summary: string;
  payload: ArticleResultVersionPayload | HumanCopyResultVersionPayload | null;
  process_summary: ProcessSummaryStep[];
  llm_audit_summary: LlmAuditSummary[];
  error_stage: string | null;
  error_summary: string | null;
  created_at: string;
}

export interface OptimizationCaseDetail {
  case: OptimizationCase;
  input: CaseInput | null;
  versions: OptimizationResultVersion[];
}

export interface CaseListFilters {
  q?: string;
  case_type?: OptimizationCaseType;
  status?: OptimizationCaseStatus;
  publish_target?: string;
  project_tag?: string;
  created_from?: string;
  created_to?: string;
  include_archived: boolean;
}

export interface CaseMetadataPatch {
  title?: string;
  customer_name?: string;
  brand_name?: string;
  project_tags?: string[];
  notes?: string;
}
