"use client";

import { useCallback, useState } from "react";

import { api } from "@/lib/api/client";
import { PROCEED, toVM, type ClarifyDecisionVM } from "./clarify";

export type ClarifyStatus = "idle" | "checking" | "asking" | "proceed" | "error";

export interface UseClarify {
  status: ClarifyStatus;
  // status=asking 时的待答问题（含选项）；其它时为 null。
  decision: ClarifyDecisionVM | null;
  // 预检：调 refine/clarify 端点，返回 VM 供调用方同步分支。失败=放行（needClarification=false），不阻塞润色。
  check: (
    projectId: string,
    chapterNo: number,
    segment: string,
    instruction: string,
  ) => Promise<ClarifyDecisionVM>;
  reset: () => void;
}

// AI 反问澄清预检（WFW-9 M1，路线A 两阶段之「问题」阶段）。
// 「再沟通」意见含糊/极短时先调独立非流式端点让 AI 反问；needClarification=false 或失败=放行去既有 refine。
export function useClarify(): UseClarify {
  const [status, setStatus] = useState<ClarifyStatus>("idle");
  const [decision, setDecision] = useState<ClarifyDecisionVM | null>(null);

  const check = useCallback<UseClarify["check"]>(
    async (projectId, chapterNo, segment, instruction) => {
      setStatus("checking");
      try {
        const { data, error } = await api.POST(
          "/projects/{project_id}/chapters/{chapter_no}/refine/clarify",
          {
            params: { path: { project_id: projectId, chapter_no: chapterNo } },
            body: { segment, instruction },
          },
        );
        if (error || !data) {
          setStatus("proceed");
          setDecision(null);
          return PROCEED;
        }
        const vm = toVM(data);
        if (vm.needClarification && vm.questions.length > 0) {
          setStatus("asking");
          setDecision(vm);
        } else {
          setStatus("proceed");
          setDecision(null);
        }
        return vm;
      } catch {
        setStatus("proceed");
        setDecision(null);
        return PROCEED;
      }
    },
    [],
  );

  const reset = useCallback((): void => {
    setStatus("idle");
    setDecision(null);
  }, []);

  return { status, decision, check, reset };
}
