import { describe, test, expect, beforeAll, afterAll } from "vitest"
import { existsSync, readFileSync, 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-e2e-${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,
  })
}

function assertPng1024(filePath: string) {
  expect(existsSync(filePath), `PNG not found: ${filePath}`).toBe(true)
  const buf = readFileSync(filePath)
  expect(buf.length).toBeGreaterThan(1000)
  expect(buf[0]).toBe(0x89)
  expect(buf[1]).toBe(0x50)
  expect(buf[2]).toBe(0x4e)
  expect(buf[3]).toBe(0x47)
  const width = buf.readUInt32BE(16)
  const height = buf.readUInt32BE(20)
  expect(width, `PNG width should be 1024, got ${width}`).toBe(1024)
  expect(height, `PNG height should be 1024, got ${height}`).toBe(1024)
}

describe("e2e — full CLI render", () => {
  test("render cover with title and icon", () => {
    const out = path.join(TMP, "e2e.png")
    const r = runCli(["render", "cover", "--title", "E2E", "--slots", "icon=mic", "--out", out, "--template-dir", "tests/fixtures"])
    expect(r.status, `stderr: ${r.stderr}`).toBe(0)
    const result = JSON.parse(r.stdout)
    expect(result.status).toBe("rendered")
    assertPng1024(out)
    const metaPath = out.replace(/\.png$/, ".meta.json")
    expect(existsSync(metaPath)).toBe(true)
    const meta = JSON.parse(readFileSync(metaPath, "utf-8"))
    expect(meta.hash).toHaveLength(64)
  })

  test("render without icon succeeds", () => {
    const out = path.join(TMP, "e2e-no-icon.png")
    const r = runCli(["render", "cover", "--title", "No Icon", "--out", out, "--template-dir", "tests/fixtures"])
    expect(r.status, `stderr: ${r.stderr}`).toBe(0)
    assertPng1024(out)
  })

  test("render with subtitle", () => {
    const out = path.join(TMP, "e2e-sub.png")
    const r = runCli(["render", "cover", "--title", "Main", "--subtitle", "Sub", "--out", out, "--template-dir", "tests/fixtures"])
    expect(r.status, `stderr: ${r.stderr}`).toBe(0)
    assertPng1024(out)
  })
})