import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { afterEach, beforeEach, describe, expect, it } from "vitest";

import {
  renderOptimizedDocx,
  renderOptimizedMarkdown,
  renderQaReportJson,
  writeJobExports,
} from "../exporter";

const article = {
  title: "Example GEO Guide",
  summary: "A factual GEO guide.",
  body_markdown: "## Body\nConfirmed content.",
  image_suggestions: [{ source: "image_1", suggestion: "Use dashboard." }],
  changed_sections: ["title"],
  requires_user_confirmation: [],
};

const qaReport = {
  overall_status: "pass" as const,
  checks: [
    {
      rule_id: "title_quality" as const,
      status: "pass" as const,
      evidence: "Readable title.",
      reason: "Title is clear.",
      suggested_fix: "",
      target_agent: null,
    },
  ],
};

describe("exporter", () => {
  let tempDir: string;

  beforeEach(() => {
    tempDir = mkdtempSync(join(tmpdir(), "geo-agent-export-"));
  });

  afterEach(() => {
    rmSync(tempDir, { recursive: true, force: true });
  });

  it("renders markdown with optimized article fields", () => {
    const markdown = renderOptimizedMarkdown(article);

    expect(markdown).toContain("# Example GEO Guide");
    expect(markdown).toContain("A factual GEO guide.");
    expect(markdown).toContain("## Body");
    expect(markdown).toContain("image_1: Use dashboard.");
  });

  it("serializes the QA report as JSON", () => {
    const json = renderQaReportJson(qaReport);

    expect(JSON.parse(json)).toMatchObject({
      overall_status: "pass",
      checks: [{ rule_id: "title_quality" }],
    });
  });

  it("creates a non-empty Word document buffer", async () => {
    const buffer = await renderOptimizedDocx(article);

    expect(buffer.byteLength).toBeGreaterThan(0);
  });

  it("writes markdown, Word, and JSON exports under a job directory", async () => {
    const paths = await writeJobExports({
      dataDir: tempDir,
      jobId: "job_xxx",
      article,
      qaReport,
    });

    expect(readFileSync(paths.markdown, "utf8")).toContain("# Example GEO Guide");
    expect(statSync(paths.docx).size).toBeGreaterThan(0);
    expect(JSON.parse(readFileSync(paths.qaJson, "utf8")).overall_status).toBe(
      "pass",
    );
    expect(paths.markdown).toContain(join("exports", "job_xxx", "optimized.md"));
  });
});
