'use client';

import { useCallback, useRef, useState } from 'react';
import { env } from '@/lib/env';
import { useAuthStore } from '@/stores/auth-store';

/** 一步工具调用(Claude 式透明步骤:看到调了哪个工具、入参、返回数据)。 */
export interface ToolStep {
  id: string;
  /** 后端 toolCallId,用于把 tool_result/tool_error 精确匹配回对应步骤(支持并行/多调用)。 */
  callId?: string;
  tool: string;
  args: unknown;
  result?: unknown;
  status: 'running' | 'done' | 'error';
  error?: string;
}

/** 模型产出的 HTML 卡片(在输出区沙箱 iframe 渲染)。 */
export interface Artifact {
  id: string;
  title?: string;
  html: string;
}

export type Block =
  | { kind: 'text'; text: string }
  | { kind: 'tool'; step: ToolStep }
  | { kind: 'artifact'; artifact: Artifact };

/** render_artifact 是本地"渲染"工具,不当普通工具步骤展示,而是渲成卡片。 */
const ARTIFACT_TOOL = 'render_artifact';

export interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  blocks: Block[];
}

export type ChatStatus = 'idle' | 'streaming' | 'error';

let _id = 0;
const nextId = () => `m${Date.now()}_${_id++}`;

/** 把 tool_result/tool_error 匹配回对应工具步骤:优先按 callId,退化到"最后一个 running"。 */
function findToolIdx(blocks: Block[], callId: string | undefined): number {
  if (callId) {
    const i = blocks.findIndex((b) => b.kind === 'tool' && b.step.callId === callId);
    if (i !== -1) return i;
  }
  for (let i = blocks.length - 1; i >= 0; i--) {
    const b = blocks[i];
    if (b && b.kind === 'tool' && b.step.status === 'running') return i;
  }
  return -1;
}

/** 把一条消息压平成后端要的 {role, content} 文本(工具块不回传,模型自行重新决策)。 */
function toApiMessage(m: ChatMessage): { role: 'user' | 'assistant'; content: string } | null {
  const text = m.blocks
    .filter((b): b is Extract<Block, { kind: 'text' }> => b.kind === 'text')
    .map((b) => b.text)
    .join('')
    .trim();
  if (!text) return null;
  return { role: m.role, content: text };
}

export function useAssistantChat() {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [status, setStatus] = useState<ChatStatus>('idle');
  const [model, setModel] = useState('deepseek');
  const abortRef = useRef<AbortController | null>(null);

  const stop = useCallback(() => {
    abortRef.current?.abort();
    abortRef.current = null;
    setStatus('idle');
  }, []);

  const send = useCallback(
    async (text: string) => {
      const trimmed = text.trim();
      if (!trimmed || status === 'streaming') return;

      const userMsg: ChatMessage = {
        id: nextId(),
        role: 'user',
        blocks: [{ kind: 'text', text: trimmed }],
      };
      const assistantId = nextId();
      const assistantMsg: ChatMessage = { id: assistantId, role: 'assistant', blocks: [] };

      // 历史(含新 user)→ apiMessages
      const apiMessages = [...messages, userMsg]
        .map(toApiMessage)
        .filter((x): x is { role: 'user' | 'assistant'; content: string } => x !== null);

      setMessages((prev) => [...prev, userMsg, assistantMsg]);
      setStatus('streaming');

      // 更新 assistant 消息 blocks 的小工具
      const patch = (fn: (blocks: Block[]) => Block[]) =>
        setMessages((prev) =>
          prev.map((m) => (m.id === assistantId ? { ...m, blocks: fn(m.blocks) } : m)),
        );

      const appendText = (t: string) =>
        patch((blocks) => {
          const last = blocks[blocks.length - 1];
          if (last && last.kind === 'text') {
            return [...blocks.slice(0, -1), { kind: 'text', text: last.text + t }];
          }
          return [...blocks, { kind: 'text', text: t }];
        });

      const onEvent = (evt: Record<string, unknown>) => {
        switch (evt.type) {
          case 'text':
            appendText((evt.text as string) ?? '');
            break;
          case 'tool_call':
            if (evt.tool === ARTIFACT_TOOL) {
              // 渲染工具:取 html/title 作为 artifact 卡片(不进工具步骤)。
              const a = (evt.args ?? {}) as { title?: string; html?: string };
              patch((blocks) => [
                ...blocks,
                { kind: 'artifact', artifact: { id: nextId(), title: a.title, html: a.html ?? '' } },
              ]);
              break;
            }
            patch((blocks) => [
              ...blocks,
              {
                kind: 'tool',
                step: {
                  id: nextId(),
                  callId: evt.id ? String(evt.id) : undefined,
                  tool: String(evt.tool ?? '工具'),
                  args: evt.args,
                  status: 'running',
                },
              },
            ]);
            break;
          case 'tool_result':
            patch((blocks) => {
              const realIdx = findToolIdx(blocks, evt.id ? String(evt.id) : undefined);
              if (realIdx === -1) return blocks;
              const b = blocks[realIdx] as Extract<Block, { kind: 'tool' }>;
              const updated: Block = {
                kind: 'tool',
                step: { ...b.step, result: evt.result, status: 'done' },
              };
              return blocks.map((x, i) => (i === realIdx ? updated : x));
            });
            break;
          case 'tool_error':
            patch((blocks) => {
              const realIdx = findToolIdx(blocks, evt.id ? String(evt.id) : undefined);
              if (realIdx === -1) return blocks;
              const b = blocks[realIdx] as Extract<Block, { kind: 'tool' }>;
              const updated: Block = {
                kind: 'tool',
                step: { ...b.step, status: 'error', error: String(evt.error ?? '工具调用出错') },
              };
              return blocks.map((x, i) => (i === realIdx ? updated : x));
            });
            break;
          case 'error':
            appendText(`\n\n⚠️ 出错:${String(evt.error)}`);
            break;
          default:
            break;
        }
      };

      const controller = new AbortController();
      abortRef.current = controller;
      try {
        const token = useAuthStore.getState().accessToken;
        const res = await fetch(new URL('/pac/v1/assistant/chat', env.apiBaseUrl), {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Accept: 'text/event-stream',
            ...(token ? { Authorization: `Bearer ${token}` } : {}),
          },
          body: JSON.stringify({ messages: apiMessages, model }),
          signal: controller.signal,
        });
        if (!res.ok || !res.body) {
          throw new Error(`HTTP ${res.status}`);
        }

        const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
        let buffer = '';
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          buffer += value;
          let sep: number;
          while ((sep = buffer.indexOf('\n\n')) !== -1) {
            const frame = buffer.slice(0, sep);
            buffer = buffer.slice(sep + 2);
            const line = frame.split('\n').find((l) => l.startsWith('data:'));
            if (!line) continue;
            const raw = line.slice('data:'.length).trim();
            if (!raw) continue;
            try {
              onEvent(JSON.parse(raw) as Record<string, unknown>);
            } catch {
              /* 忽略半截帧 */
            }
          }
        }
        setStatus('idle');
      } catch (err) {
        if ((err as Error).name !== 'AbortError') {
          appendText(`\n\n⚠️ 连接失败:${(err as Error).message}`);
          setStatus('error');
        } else {
          setStatus('idle');
        }
      } finally {
        abortRef.current = null;
      }
    },
    [messages, model, status],
  );

  return { messages, status, model, setModel, send, stop };
}
