<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";

import { reviewApi, type AssistantMessage } from "../../shared/api/review";
import { useMarketStore } from "../../shared/stores/market";
import { useSessionStore } from "../../shared/stores/session";
import { useUiStore } from "../../shared/stores/ui";

const market = useMarketStore();
const session = useSessionStore();
const ui = useUiStore();
const messages = ref<AssistantMessage[]>([]);
const question = ref("");
const loading = ref(false);
const historyLoading = ref(false);
const historyError = ref("");
const messageRoot = ref<HTMLElement | null>(null);
let controller: AbortController | undefined;
const locked = computed(() => !session.account?.smart_access);
const prompts: Array<[string, string]> = [
  ["市场位置", "结合近十日情绪和今天的数据，当前市场处于什么位置？"],
  ["市场主线", "总结当前市场主线，并说明证据和可能的失效条件。"],
  ["交易复盘", "结合我的策略跟踪和交易日志，找出最值得修正的一个行为模式。"],
  ["明日清单", "为下一个交易日给出条件化观察清单，不给无条件买卖指令。"],
];
async function load(): Promise<void> {
  if (locked.value) return;
  historyLoading.value = true;
  historyError.value = "";
  try { messages.value = await reviewApi.assistantMessages(); }
  catch (reason) { historyError.value = reason instanceof Error ? reason.message : "对话读取失败"; }
  finally { historyLoading.value = false; }
}
async function send(): Promise<void> {
  const value = question.value.trim();
  if (!value || loading.value || locked.value) return;
  question.value = "";
  const user = { id: Date.now(), role: "user", content: value, context_date: market.selectedDate, status: "complete", created_at: "" } as AssistantMessage;
  const answer = { id: Date.now() + 1, role: "assistant", content: "", context_date: market.selectedDate, status: "complete", created_at: "" } as AssistantMessage;
  messages.value.push(user, answer);
  loading.value = true;
  controller = new AbortController();
  try {
    await reviewApi.chat(market.selectedDate, value, (event) => {
      if (event.type === "delta") answer.content += event.content ?? "";
      if (event.type === "error") ui.showToast(event.message ?? "复盘助手回答中断");
      void scrollEnd();
    }, controller.signal);
  } catch (reason) {
    if (!(reason instanceof DOMException && reason.name === "AbortError")) ui.showToast(reason instanceof Error ? reason.message : "回答失败");
  } finally { loading.value = false; controller = undefined; }
}
async function clear(): Promise<void> {
  await reviewApi.clearAssistant(); messages.value = [];
}
function usePrompt(value: string): void { question.value = value; }
function stop(): void { controller?.abort(); }
async function scrollEnd(): Promise<void> { await nextTick(); if (messageRoot.value) messageRoot.value.scrollTop = messageRoot.value.scrollHeight; }
onMounted(load);
</script>

<template>
  <div class="assistant-panel">
    <div v-if="locked" class="notice notice-warning"><strong>复盘助手仅对会员开放</strong><span>开通会员后可读取市场统计、策略跟踪与个人复盘记录，进行统一复盘分析。</span></div>
    <div class="assistant-content" :class="{ 'locked-content': locked }" :aria-disabled="locked">
      <div ref="messageRoot" class="assistant-messages"><div v-if="historyLoading" class="assistant-empty">正在读取复盘助手对话</div><div v-else-if="historyError" class="assistant-empty"><strong>复盘助手对话暂不可用</strong><p>{{ historyError }}</p></div><template v-else><article v-for="message in messages" :key="message.id" :class="message.role"><span>{{ message.role === 'user' ? '我' : '复盘助手' }}</span><p>{{ message.content || (loading ? "正在整理复盘材料" : "") }}</p></article><div v-if="!messages.length" class="assistant-empty">可以从市场、策略或自己的交易记录开始复盘</div></template></div>
      <div class="assistant-prompts"><button v-for="item in prompts" :key="item[0]" type="button" :disabled="locked" @click="usePrompt(item[1])">{{ item[0] }}</button></div>
      <form class="assistant-compose" @submit.prevent="send"><textarea v-model="question" class="textarea" maxlength="2000" placeholder="询问市场位置、主线、策略表现或自己的交易模式" :disabled="locked" required></textarea><div><button v-if="loading" class="btn" type="button" @click="stop">停止</button><button v-else class="btn btn-primary" type="submit" :disabled="locked">发送</button><button class="btn btn-ghost" type="button" :disabled="locked" @click="clear">清空对话</button></div></form>
    </div>
  </div>
</template>
