import { useCallback, useState } from 'react';
import { tarotInterpret, tarotSaveReading } from '../../../api';

const ELEMENTS = ['air', 'water', 'fire', 'earth'];

export function buildReferenceBlock(picks) {
  return picks
    .map((p, i) => {
      const c = p.card;
      const orient = p.reversed ? '역방향' : '정방향';
      const arcana = c.arcana === 'major'
        ? `Major (${c.id})`
        : `Minor (${c.suit}, ${c.rank})`;
      const kw = p.reversed ? c.reversedKeywords : c.keywords;
      const meaning = p.reversed ? c.meaningReversed : c.meaningUpright;
      return [
        `## ${i + 1}. 위치: ${p.position} | 카드: ${c.nameEn} (${orient})`,
        `- 아르카나: ${arcana}`,
        `- 원소: ${c.element || '없음'}`,
        `- ${orient} 키워드: ${(kw || []).join(', ')}`,
        `- ${orient} 의미: ${meaning}`,
      ].join('\n');
    })
    .join('\n\n');
}

export function buildContextMeta(picks) {
  const majors = picks.filter((p) => p.card.arcana === 'major').length;
  const minors = picks.length - majors;
  const elementDist = ELEMENTS.reduce((acc, e) => ({ ...acc, [e]: 0 }), {});
  for (const p of picks) {
    const e = p.card.element;
    if (e && elementDist[e] !== undefined) elementDist[e] += 1;
  }
  const flow = picks.map((p) => (p.reversed ? 'reversed' : 'upright')).join('→');
  return {
    major_minor_ratio: `${majors}:${minors}`,
    element_distribution: elementDist,
    orientation_flow: flow,
  };
}

export function useTarotReading() {
  const [status, setStatus] = useState('idle');
  const [interpretation, setInterpretation] = useState(null);
  const [readingId, setReadingId] = useState(null);
  const [error, setError] = useState(null);

  const runInterpretAndSave = useCallback(async ({ spread_type, category, question, picks }) => {
    setStatus('interpreting');
    setError(null);
    setInterpretation(null);
    setReadingId(null);

    const cards = picks.map((p) => ({
      position: p.position,
      card_id: p.card.slug,
      reversed: !!p.reversed,
    }));
    const reference = buildReferenceBlock(picks);
    const meta = buildContextMeta(picks);

    let interp;
    try {
      interp = await tarotInterpret({
        spread_type, category, question, cards,
        cards_reference: reference,
        context_meta: meta,
      });
    } catch (e) {
      setStatus('failed');
      setError(e.message || String(e));
      throw e;
    }

    setInterpretation(interp.interpretation_json);
    setStatus('saving');

    try {
      const saved = await tarotSaveReading({
        spread_type, category, question, cards,
        interpretation_json: interp.interpretation_json,
        model: interp.model,
        tokens_in: interp.tokens_in,
        tokens_out: interp.tokens_out,
        cost_usd: interp.cost_usd,
        confidence: interp.interpretation_json.confidence,
      });
      setReadingId(saved.id);
      setStatus('done');
    } catch (e) {
      setStatus('save_failed');
      setError(e.message || String(e));
    }

    return interp.interpretation_json;
  }, []);

  return { status, interpretation, readingId, error, runInterpretAndSave };
}
