// SPEC: PJ2026-01040409 MDTODO前端重写; draft-2026-06-26-p0-mdtodo-web-rewrite.
// Responsibility: report link preview, fullscreen and close/restore via public API.

import { ref } from "vue";
import DOMPurify from "dompurify";
import { marked } from "marked";
import { projectManagementAPI, type MdtodoReportPreviewRecord, type MdtodoTaskLinkRecord } from "@/api";

/**
 * Parses task-body Markdown links into report links, opens the right-pane
 * preview, supports fullscreen and close-restore. Reports use a mature Markdown
 * renderer with sanitization and light Workbench-style code blocks; long
 * JSON/RPC scrolls inside the pane. Report files never enter the File dropdown.
 */
export function useMdtodoReportPreview() {
  const reportPreview = ref<MdtodoReportPreviewRecord | null>(null);
  const activeReportLink = ref<MdtodoTaskLinkRecord | null>(null);
  const reportLoading = ref(false);
  const reportError = ref<string | null>(null);
  const showReportFullscreen = ref(false);

  function markdownToHtml(value?: string | null): string {
    const text = String(value ?? "").trim();
    if (!text) return "";
    return DOMPurify.sanitize(marked.parse(text, { async: false }) as string);
  }

  function projectedLinkNeedsRefresh(link: MdtodoTaskLinkRecord): boolean {
    return link.availability === "projected-link-unavailable";
  }

  function openProjectedLinkPlaceholder(link: MdtodoTaskLinkRecord): MdtodoReportPreviewRecord {
    const message = link.message || "任务投影确认存在报告链接，但当前缓存缺少报告目标；恢复 HWPOD 详情读取或重建 MDTODO 索引后可打开完整报告。";
    const content = `## 报告索引待刷新\n\n${message}\n\n- 报告: ${link.label || link.linkId}\n- 状态: projection-only\n`;
    const report: MdtodoReportPreviewRecord = {
      content,
      fingerprint: `projected:${link.linkId}`,
      revision: `projected:${link.linkId}`,
      byteCount: content.length,
      render: "markdown",
      linkId: link.linkId,
      label: link.label,
      href: link.href,
      valuesRedacted: true
    };
    reportPreview.value = report;
    activeReportLink.value = link;
    reportError.value = null;
    return report;
  }

  async function openReportPreview(taskRef: string, link: MdtodoTaskLinkRecord): Promise<MdtodoReportPreviewRecord | null> {
    if (!link.linkId || link.kind !== "markdown-report") return null;
    if (projectedLinkNeedsRefresh(link)) return openProjectedLinkPlaceholder(link);
    reportLoading.value = true;
    reportError.value = null;
    try {
      const response = await projectManagementAPI.reportPreview(taskRef, link.linkId);
      if (!response.ok) throw response;
      const report = response.data?.report ?? null;
      if (!report?.content) throw new Error("报告内容未返回");
      reportPreview.value = report;
      activeReportLink.value = response.data?.link ?? link;
      return report;
    } catch (err) {
      reportError.value = err && typeof err === "object" && "error" in err ? String((err as { error?: string }).error || "报告加载失败") : "报告加载失败";
      return null;
    } finally {
      reportLoading.value = false;
    }
  }

  async function openReportPreviewById(taskRef: string, links: MdtodoTaskLinkRecord[], linkId: string): Promise<MdtodoReportPreviewRecord | null> {
    const target = links.find((link) => link.linkId === linkId || link.label === linkId || link.relativePath?.includes(linkId) || link.href?.includes(linkId));
    if (!target) {
      reportError.value = `报告链接未找到: ${linkId}`;
      return null;
    }
    return openReportPreview(taskRef, target);
  }

  function closeReportPreview(): void {
    reportPreview.value = null;
    activeReportLink.value = null;
    showReportFullscreen.value = false;
    reportError.value = null;
  }

  function openFullscreen(): void {
    if (reportPreview.value) showReportFullscreen.value = true;
  }

  function closeFullscreen(): void {
    showReportFullscreen.value = false;
  }

  return {
    reportPreview,
    activeReportLink,
    reportLoading,
    reportError,
    showReportFullscreen,
    markdownToHtml,
    openReportPreview,
    openReportPreviewById,
    closeReportPreview,
    openFullscreen,
    closeFullscreen
  };
}
