import { newId } from "../../lib/id";
import { readJson, writeJson } from "../../lib/storage";
import { nowUnixNano } from "../../lib/time";
import type { PlayStep, ThreadPlay } from "../../domain/types";
import { KEYS } from "../../data/mock/keys";

export type WizardDraft = {
  playId: string;
  stepIndex: number;
  title: string;
  topic: string;
  lead_account_id: string;
  cast_account_ids: string[];
  steps: PlayStep[];
  schedule_start_at: number;
  interval_minutes: number;
};

/** i18n keys; translate with t(key) in Stepper / Wizard UI */
export const WIZARD_STEPS = [
  "wizard.step.topic",
  "wizard.step.crew",
  "wizard.step.script",
  "wizard.step.preview",
  "wizard.step.schedule",
  "wizard.step.submit",
] as const;

export function emptyDraft(): WizardDraft {
  const lead = "";
  const rootId = newId("step");
  return {
    playId: newId("play"),
    stepIndex: 0,
    title: "",
    topic: "",
    lead_account_id: lead,
    cast_account_ids: [],
    steps: [
      {
        id: rootId,
        sort_order: 0,
        kind: "root",
        account_id: lead,
        text: "",
        delay_from_previous_sec: 0,
      },
    ],
    // 第一則預設立刻；後續步靠 interval + 後端抖動
    schedule_start_at: nowUnixNano(),
    interval_minutes: 5,
  };
}

function draftKey(scope: string): string {
  return `${KEYS.playDraft}:${scope}`;
}

export function loadDraft(scope = "new"): WizardDraft {
  const raw = readJson<WizardDraft | null>(draftKey(scope), null);
  if (!raw || typeof raw !== "object" || !Array.isArray(raw.steps)) {
    return emptyDraft();
  }
  return raw;
}

export function saveDraft(draft: WizardDraft, scope = "new"): void {
  writeJson(draftKey(scope), draft);
}

export function clearDraft(scope = "new"): void {
  writeJson(draftKey(scope), emptyDraft());
}

export function applyIntervalToSteps(steps: PlayStep[], intervalMinutes: number): PlayStep[] {
  const sec = Math.max(0, Math.floor(intervalMinutes * 60));
  return steps.map((s, i) => ({
    ...s,
    sort_order: i,
    delay_from_previous_sec: i === 0 ? 0 : sec,
  }));
}

export function draftToPlay(draft: WizardDraft, untitledFallback = "Untitled play"): ThreadPlay {
  const now = nowUnixNano();
  const steps = applyIntervalToSteps(
    draft.steps.map((s, i) =>
      i === 0
        ? { ...s, kind: "root" as const, account_id: draft.lead_account_id, sort_order: 0 }
        : { ...s, kind: "reply" as const, sort_order: i },
    ),
    draft.interval_minutes,
  );
  return {
    id: draft.playId,
    title: draft.title.trim() || draft.topic.trim() || untitledFallback,
    topic: draft.topic.trim(),
    status: "draft",
    lead_account_id: draft.lead_account_id,
    cast_account_ids: draft.cast_account_ids,
    steps,
    schedule_start_at: draft.schedule_start_at,
    created_at: now,
    updated_at: now,
  };
}
