#!/usr/bin/env node

import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
import { arch, cpus, platform, release, totalmem } from 'node:os';
import { basename, extname, join, relative, resolve } from 'node:path';
import { spawn } from 'node:child_process';
import { performance } from 'node:perf_hooks';
import { selectVisualReview } from './select-visual-review.mjs';

const ROOT = resolve(import.meta.dirname, '..');
const MANIFEST_PATH = join(ROOT, 'manifest.csv');
const RESULTS_PATH = join(ROOT, 'results.csv');
const SUMMARY_PATH = join(ROOT, 'summary.csv');
const TOOLS_DIR = join(ROOT, '.tools');
const WORK_ROOT = join(ROOT, '.work', new Date().toISOString().replaceAll(/[:.]/g, '-'));
const RUNS = 3;
const PIPIC_VERSION = '1.0.6';
const SHARP_VERSION = '0.35.3';

const RESULT_HEADER = [
  'run_date', 'machine', 'tool', 'tool_version', 'input_id', 'command', 'status',
  'input_bytes', 'output_bytes', 'saved_bytes', 'duration_ms', 'notes',
];
const SUMMARY_HEADER = [
  'run_date', 'machine', 'tool', 'tool_version', 'input_id', 'runs', 'status',
  'input_bytes', 'median_output_bytes', 'median_saved_bytes', 'median_duration_ms', 'notes',
];

function csv(value) {
  const text = String(value ?? '');
  return /[",\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
}

function parseCsv(text) {
  const rows = [];
  let row = [];
  let field = '';
  let quoted = false;
  for (let i = 0; i < text.length; i++) {
    const char = text[i];
    if (quoted) {
      if (char === '"' && text[i + 1] === '"') {
        field += '"';
        i++;
      } else if (char === '"') quoted = false;
      else field += char;
    } else if (char === '"') quoted = true;
    else if (char === ',') {
      row.push(field);
      field = '';
    } else if (char === '\n') {
      row.push(field.replace(/\r$/, ''));
      if (row.some(Boolean)) rows.push(row);
      row = [];
      field = '';
    } else field += char;
  }
  if (field || row.length) {
    row.push(field);
    rows.push(row);
  }
  const [header, ...body] = rows;
  return body.map((values) => Object.fromEntries(header.map((key, index) => [key, values[index] ?? ''])));
}

function renderCsv(header, rows) {
  return `${header.join(',')}\n${rows.map((row) => header.map((key) => csv(row[key])).join(',')).join('\n')}\n`;
}

function run(command, args, options = {}) {
  return new Promise((resolveRun, reject) => {
    const started = performance.now();
    const child = spawn(command, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] });
    let stdout = '';
    let stderr = '';
    child.stdout.on('data', (chunk) => (stdout += chunk));
    child.stderr.on('data', (chunk) => (stderr += chunk));
    child.on('error', reject);
    child.on('close', (code) => resolveRun({
      code,
      stdout,
      stderr,
      durationMs: Math.round((performance.now() - started) * 1000) / 1000,
    }));
  });
}

async function machineLabel() {
  let system = `${platform()} ${release()}`;
  if (platform() === 'darwin') {
    const sw = await run('sw_vers', ['-productVersion']);
    if (sw.code === 0) system = `macOS ${sw.stdout.trim()}`;
  }
  const cpu = cpus()[0]?.model ?? 'unknown CPU';
  const gib = Math.round(totalmem() / 1024 / 1024 / 1024);
  return `${system}; ${cpu}; ${gib} GiB; ${arch()}`;
}

async function ensureTools() {
  await mkdir(TOOLS_DIR, { recursive: true });
  const packageJson = {
    private: true,
    type: 'module',
    dependencies: {
      '@pipic/cli': PIPIC_VERSION,
      sharp: SHARP_VERSION,
    },
  };
  await writeFile(join(TOOLS_DIR, 'package.json'), `${JSON.stringify(packageJson, null, 2)}\n`);
  const install = await run('npm', ['install', '--ignore-scripts=false', '--package-lock=false', '--no-audit', '--no-fund'], { cwd: TOOLS_DIR });
  if (install.code !== 0) throw new Error(`tool install failed\n${install.stderr || install.stdout}`);

  const pipicEntry = join(TOOLS_DIR, 'node_modules', '@pipic', 'cli', 'dist', 'pipic.mjs');
  const sharpEntry = join(TOOLS_DIR, 'node_modules', 'sharp', 'dist', 'index.mjs');
  const installedPiPic = JSON.parse(await readFile(join(TOOLS_DIR, 'node_modules', '@pipic', 'cli', 'package.json'), 'utf8')).version;
  const installedSharp = JSON.parse(await readFile(join(TOOLS_DIR, 'node_modules', 'sharp', 'package.json'), 'utf8')).version;
  if (installedPiPic !== PIPIC_VERSION || installedSharp !== SHARP_VERSION) {
    throw new Error(`version mismatch: PiPic ${installedPiPic}, sharp ${installedSharp}`);
  }
  return { pipicEntry, sharpEntry };
}

async function assertQuota(pipicEntry, inputCount) {
  const quota = await run(process.execPath, [pipicEntry, 'quota']);
  if (quota.code !== 0) throw new Error(`PiPic authentication/quota check failed\n${quota.stderr || quota.stdout}`);
  const remaining = Number(quota.stdout.match(/\((\d+) left\)/)?.[1]);
  const needed = inputCount * RUNS;
  if (!Number.isFinite(remaining) || remaining < needed) {
    throw new Error(`PiPic needs ${needed} remaining images for this run; quota output was:\n${quota.stdout}`);
  }
  console.log(`PiPic quota gate passed: ${needed} runs required, ${remaining} remaining`);
}

async function decode(path, expectedMime) {
  const probe = await run('ffprobe', [
    '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=codec_name,width,height', '-of', 'json', path,
  ]);
  if (probe.code !== 0) return { ok: false, note: probe.stderr.trim() || 'ffprobe failed' };
  const stream = JSON.parse(probe.stdout).streams?.[0];
  const expected = new Map([
    ['image/png', 'png'],
    ['image/jpeg', 'mjpeg'],
    ['image/webp', 'webp'],
    ['image/avif', 'av1'],
  ]).get(expectedMime);
  return {
    ok: Boolean(stream?.width && stream?.height && stream.codec_name === expected),
    note: `decoded=${stream?.codec_name ?? 'unknown'} ${stream?.width ?? 0}x${stream?.height ?? 0}`,
  };
}

function median(values) {
  const sorted = [...values].sort((a, b) => a - b);
  return sorted[Math.floor(sorted.length / 2)];
}

const manifest = parseCsv(await readFile(MANIFEST_PATH, 'utf8'));
if (manifest.length !== 12) throw new Error(`expected 12 manifest inputs, found ${manifest.length}`);

const { pipicEntry, sharpEntry } = await ensureTools();
await assertQuota(pipicEntry, manifest.length);
await mkdir(WORK_ROOT, { recursive: true });
const machine = await machineLabel();
const runDate = new Intl.DateTimeFormat('en-CA', {
  timeZone: 'Asia/Shanghai',
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
}).format(new Date());
const results = [];

for (let runIndex = 1; runIndex <= RUNS; runIndex++) {
  for (const input of manifest) {
    const inputPath = join(ROOT, input.filename);
    const inputBytes = Number(input.input_bytes);
    const format = extname(input.filename).slice(1);

    for (const tool of ['pipic', 'sharp']) {
      const outputDir = join(WORK_ROOT, tool, `run-${runIndex}`, input.id);
      await mkdir(outputDir, { recursive: true });
      const outputPath = join(outputDir, basename(inputPath));
      let command;
      let execution;
      let rawStatus = 'ok';
      let note = `run=${runIndex}/${RUNS}`;
      let hasStructuredOutput = false;

      if (tool === 'pipic') {
        const args = [pipicEntry, inputPath, '-o', outputDir, '--json', '--concurrency', '1'];
        command = `node .tools/node_modules/@pipic/cli/dist/pipic.mjs ${relative(ROOT, inputPath)} -o ${relative(ROOT, outputDir)} --json --concurrency 1`;
        execution = await run(process.execPath, args);
        const jsonLine = execution.stdout.trim().split('\n').filter(Boolean).at(-1);
        try {
          const item = JSON.parse(jsonLine || '{}');
          hasStructuredOutput = true;
          rawStatus = item.status || (execution.code === 0 ? 'error' : 'error');
          if (item.error) note += `; cli=${item.error}`;
        } catch {
          rawStatus = 'error';
          note += '; invalid PiPic NDJSON';
        }
      } else {
        const script = join(ROOT, 'scripts', 'sharp-compress.mjs');
        const args = [script, inputPath, outputPath, format, sharpEntry];
        command = `node scripts/sharp-compress.mjs ${relative(ROOT, inputPath)} ${relative(ROOT, outputPath)} ${format} .tools/node_modules/sharp/dist/index.mjs`;
        execution = await run(process.execPath, args);
        rawStatus = execution.code === 0 ? 'ok' : 'error';
      }

      let outputBytes = 0;
      let decodeResult = { ok: false, note: 'output missing' };
      try {
        outputBytes = (await stat(outputPath)).size;
        decodeResult = await decode(outputPath, input.mime_type);
      } catch {
        // Failed command: keep the machine-readable zero values.
      }

      if (execution.code !== 0 || !decodeResult.ok) rawStatus = 'error';
      else if (tool === 'sharp' && outputBytes >= inputBytes) rawStatus = 'not_smaller';
      const diagnostic = execution.stderr || (hasStructuredOutput ? '' : execution.stdout);
      const stderr = execution.code === 0 ? '' : diagnostic.trim().replaceAll(ROOT, '.').replaceAll(/\s+/g, ' ').slice(0, 300);
      note += `; ${decodeResult.note}`;
      if (stderr) note += `; process=${stderr}`;

      const savedBytes = rawStatus === 'error' ? 0 : Math.max(0, inputBytes - outputBytes);
      results.push({
        run_date: runDate,
        machine,
        tool: tool === 'pipic' ? 'PiPic Agent CLI' : 'sharp',
        tool_version: tool === 'pipic' ? PIPIC_VERSION : SHARP_VERSION,
        input_id: input.id,
        command,
        status: rawStatus,
        input_bytes: inputBytes,
        output_bytes: outputBytes,
        saved_bytes: savedBytes,
        duration_ms: execution.durationMs,
        notes: note,
      });
      console.log(`${runIndex}/${RUNS} ${tool} ${input.id}: ${rawStatus}, ${inputBytes} -> ${outputBytes} bytes, ${execution.durationMs} ms`);
    }
  }
}

await writeFile(RESULTS_PATH, renderCsv(RESULT_HEADER, results));

const groups = new Map();
for (const row of results) {
  const key = `${row.tool}\0${row.input_id}`;
  const group = groups.get(key) ?? [];
  group.push(row);
  groups.set(key, group);
}
const summary = [...groups.values()].map((group) => {
  const failures = group.filter((row) => row.status === 'error').length;
  return {
    run_date: runDate,
    machine,
    tool: group[0].tool,
    tool_version: group[0].tool_version,
    input_id: group[0].input_id,
    runs: group.length,
    status: failures ? 'has_errors' : group.some((row) => row.status === 'not_smaller' || row.status === 'skipped') ? 'includes_not_smaller' : 'ok',
    input_bytes: group[0].input_bytes,
    median_output_bytes: median(group.map((row) => row.output_bytes)),
    median_saved_bytes: median(group.map((row) => row.saved_bytes)),
    median_duration_ms: median(group.map((row) => row.duration_ms)),
    notes: failures ? `${failures}/${group.length} runs failed` : 'median of three consecutive end-to-end runs',
  };
});
await writeFile(SUMMARY_PATH, renderCsv(SUMMARY_HEADER, summary));

const visualRows = await selectVisualReview({ workRoot: WORK_ROOT, manifest, results });

console.log(`wrote ${results.length} raw rows to ${RESULTS_PATH}`);
console.log(`wrote ${summary.length} median rows to ${SUMMARY_PATH}`);
console.log(`wrote ${visualRows.length} visual-audit selections to ${join(ROOT, 'visual-review.csv')}`);
console.log(`local outputs remain under ${WORK_ROOT}`);
