/**
 * commands/variant-pick.mjs — `apt-tools variant-pick <task-dir> <letter>` (C1, Wave 2).
 *
 * Promotes one variant from a `--variants N` run to the canonical
 * iteration file and archives the others.  Called by `/apt:mockup --pick`
 * (the skill does the user-facing prompt + next-step messaging; this
 * command does the deterministic filesystem work).
 *
 * Usage:
 *
 *   apt-tools variant-pick <task-dir> <letter>                 # latest iteration
 *   apt-tools variant-pick <task-dir> <letter> --iteration 002
 *
 * Output envelope (stdout):
 *
 *   {
 *     status: "ok",
 *     command: "variant-pick",
 *     iteration: "001",
 *     letter: "b",
 *     promoted: "<abs path to iteration-001.html>",
 *     source: "<abs path to iteration-001-variant-b.html>",
 *     archive_dir: "<abs path to iteration-001-archive/>",
 *     archived: [string, ...]
 *   }
 */

import { existsSync, readdirSync } from 'node:fs'
import { resolve as resolvePath } from 'node:path'
import { parseFlags } from '../util/args.mjs'
import { err, ok } from '../util/result.mjs'
import { promoteVariant } from '../variant/pick.mjs'

function detectLatestIteration(entries) {
	const re = /^iteration-(\d{3})-variant-[a-z]\.html$/i
	const seen = new Set()
	for (const name of entries) {
		const m = name.match(re)
		if (m) seen.add(m[1])
	}
	if (seen.size === 0) return null
	const sorted = [...seen].sort()
	return sorted[sorted.length - 1] ?? null
}

export function cmdVariantPick(taskDirArg, letterArg, extraArgs) {
	if (
		!taskDirArg ||
		typeof taskDirArg !== 'string' ||
		taskDirArg.startsWith('--') ||
		!letterArg ||
		typeof letterArg !== 'string' ||
		letterArg.startsWith('--')
	) {
		return err('Usage: apt-tools variant-pick <task-dir> <letter> [--iteration NNN]')
	}

	const letterRaw = letterArg.trim().toLowerCase()
	if (!/^[a-z]$/.test(letterRaw)) {
		return err(`variant-pick: <letter> must be a single letter (a-z), got "${letterArg}"`)
	}

	const flags = parseFlags(extraArgs ?? [])
	const iterationFlag = flags.get('iteration')

	const taskDir = resolvePath(process.cwd(), taskDirArg)
	const mockupsDir = resolvePath(taskDir, 'mockups')
	if (!existsSync(mockupsDir)) {
		return err(`variant-pick: mockups directory does not exist at ${mockupsDir}`)
	}

	let iteration
	if (typeof iterationFlag === 'string' && /^\d{1,3}$/.test(iterationFlag)) {
		iteration = iterationFlag.padStart(3, '0')
	} else {
		const entries = readdirSync(mockupsDir)
		iteration = detectLatestIteration(entries)
		if (!iteration) {
			return err(
				`variant-pick: no iteration-NNN-variant-X.html files under ${mockupsDir}. Run \`/apt:mockup --variants N\` first.`,
			)
		}
	}

	let result
	try {
		result = promoteVariant({ mockupsDir, iteration, letter: letterRaw })
	} catch (e) {
		const msg = e instanceof Error ? e.message : String(e)
		return err(`variant-pick: ${msg}`)
	}

	return ok({
		status: 'ok',
		command: 'variant-pick',
		iteration: result.iteration,
		letter: result.letter,
		promoted: result.promoted,
		source: result.source,
		archive_dir: result.archiveDir,
		archived: result.archived,
	})
}
