import { useState } from 'react';
import { runScreener } from '../../../../api';

const MAX_PREVIEW_HISTORY = 10;

export function useScreenerRun() {
  const [result, setResult] = useState(null);
  const [running, setRunning] = useState(false);
  // 미리보기 결과를 세션 메모리에 누적 (새로고침 시 사라짐 — DB 부하 없음)
  const [previewHistory, setPreviewHistory] = useState([]);

  async function call(mode, settings) {
    setRunning(true);
    try {
      const body = {
        mode,
        weights: settings.weights,
        node_params: settings.node_params,
        gate_params: settings.gate_params,
        top_n: settings.top_n,
      };
      const r = await runScreener(body);
      setResult(r);
      const stamp = new Date().toISOString();
      const item = {
        id: `${mode}-${stamp}`,
        mode,
        timestamp: stamp,
        asof: r?.asof,
        survivors_count: r?.survivors_count,
        top_ticker: r?.results?.[0]?.ticker,
        top_name: r?.results?.[0]?.name,
        top_score: r?.results?.[0]?.total_score,
        result: r,
      };
      setPreviewHistory((prev) => [item, ...prev].slice(0, MAX_PREVIEW_HISTORY));
      return r;
    } finally {
      setRunning(false);
    }
  }

  function selectPreview(id) {
    const item = previewHistory.find((p) => p.id === id);
    if (item) setResult(item.result);
  }

  return {
    result, running, previewHistory,
    runPreview: (s) => call('preview', s),
    runSave:    (s) => call('manual_save', s),
    selectPreview,
  };
}
