import type {
  OptimizationFactCard,
  OptimizedArticle,
  QaReport,
} from "../domain/types";

export type OptimizationStreamStage =
  | "input"
  | "job"
  | "fact_card"
  | "draft"
  | "qa"
  | "rewrite"
  | "final";

export type OptimizationStreamEvent =
  | {
      type: "job_created";
      job: { id: string };
      case?: { id: string; case_type: "article" };
    }
  | {
      type: "fact_card_ready";
      job_id: string;
      fact_card: OptimizationFactCard;
    }
  | { type: "draft_started"; job_id: string; message: string }
  | { type: "draft_ready"; job_id: string; article: OptimizedArticle }
  | { type: "qa_started"; job_id: string; message: string }
  | { type: "qa_ready"; job_id: string; qa_report: QaReport }
  | { type: "rewrite_started"; job_id: string; round: number }
  | {
      type: "rewrite_ready";
      job_id: string;
      round: number;
      article: OptimizedArticle;
    }
  | {
      type: "final_ready";
      job_id: string;
      case?: { id: string; case_type: "article" };
      result_version?: { id: string; version: number };
      optimized_article: OptimizedArticle;
      qa_report: QaReport;
      export_paths: Record<string, string>;
    }
  | {
      type: "failed";
      job_id?: string;
      case?: { id: string; case_type: "article" };
      result_version?: { id: string; version: number };
      stage: OptimizationStreamStage;
      error: string;
    };

export function encodeOptimizationStreamEvent(
  event: OptimizationStreamEvent,
) {
  return `${JSON.stringify(event)}\n`;
}

export function parseOptimizationStreamChunk(
  previousRemainder: string,
  chunk: string,
) {
  const text = previousRemainder + chunk;
  const lines = text.split(/\n/);
  const remainder = lines.pop() ?? "";
  const events = lines
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => JSON.parse(line) as OptimizationStreamEvent);

  return { events, remainder };
}
