import { describe, test, expect, beforeAll, afterAll } from "vitest"
import { existsSync, readdirSync, rmSync, mkdirSync } from "node:fs"
import path from "node:path"
import os from "node:os"
import { fileURLToPath } from "node:url"
import { spawnSync } from "node:child_process"

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const DRAW_IMAGE_DIR = path.resolve(__dirname, "..")
const TMP = path.join(os.tmpdir(), `draw-image-cleanup-${process.pid}`)

beforeAll(() => {
  if (existsSync(TMP)) rmSync(TMP, { recursive: true, force: true })
  mkdirSync(TMP, { recursive: true })
})

afterAll(() => {
  if (existsSync(TMP)) rmSync(TMP, { recursive: true, force: true })
})

function runCli(args: string[]): { status: number; stdout: string; stderr: string } {
  return spawnSync("node", ["--experimental-strip-types", path.join(DRAW_IMAGE_DIR, "cli.ts"), ...args], {
    encoding: "utf-8",
    cwd: DRAW_IMAGE_DIR,
  })
}

describe("cleanup — temp SVG after render", () => {
  test("no .tmp-render.svg left in draw-image dir after CLI render", () => {
    const out = path.join(TMP, "cleanup.png")
    const leftoverPath = path.join(DRAW_IMAGE_DIR, ".tmp-render.svg")
    if (existsSync(leftoverPath)) rmSync(leftoverPath, { force: true })

    const r = runCli(["render", "cover", "--title", "Cleanup", "--out", out, "--template-dir", "tests/fixtures"])
    expect(r.status, `stderr: ${r.stderr}`).toBe(0)

    expect(existsSync(leftoverPath), ".tmp-render.svg must not remain in package dir").toBe(false)
  })

  test("unique temp SVG uses process pid under os.tmpdir and is removed", () => {
    const expectedTmp = path.join(os.tmpdir(), `draw-image-${process.pid}.svg`)
    if (existsSync(expectedTmp)) rmSync(expectedTmp, { force: true })

    const out = path.join(TMP, "pid.png")
    const r = runCli(["render", "cover", "--title", "Pid Check", "--out", out, "--template-dir", "tests/fixtures"])
    expect(r.status, `stderr: ${r.stderr}`).toBe(0)

    expect(existsSync(expectedTmp), `temp svg at ${expectedTmp} must be cleaned up`).toBe(false)
  })

  test("package dir contains no stray .svg files after render", () => {
    const out = path.join(TMP, "no-stray.png")
    const r = runCli(["render", "cover", "--title", "No Stray", "--out", out, "--template-dir", "tests/fixtures"])
    expect(r.status, `stderr: ${r.stderr}`).toBe(0)

    const stray = readdirSync(DRAW_IMAGE_DIR).filter((f) => f.startsWith(".tmp") && f.endsWith(".svg"))
    expect(stray, `stray temp svg files: ${stray.join(", ")}`).toEqual([])
  })
})