/**
 * variant/pick.mjs — promote one variant to the iteration's canonical file.
 *
 * Pure-ish helper used by `apt-tools variant-pick`: takes a mockups dir,
 * an iteration number, and a winning letter, then:
 *
 *   1. Copies   iteration-NNN-variant-<letter>.html → iteration-NNN.html
 *      (not move — the source is preserved under the archive so the user
 *      can always re-check which variant they promoted).
 *   2. Moves the losing variants and the gallery file into
 *      iteration-NNN-archive/ under the same mockups directory.
 *   3. Appends a structured entry to mockup_log.md if it exists.
 *
 * Returns a structured summary so the CLI dispatcher can emit it verbatim.
 */
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, } from 'node:fs';
import { resolve as resolvePath } from 'node:path';
const VARIANT_RE = /^iteration-(\d{3})-variant-([a-z])\.html$/i;
const GALLERY_RE = /^iteration-(\d{3})-gallery\.html$/;
/**
 * @typedef {object} PickResult
 * @property {string} promoted        — absolute path of the new iteration-NNN.html
 * @property {string} source          — absolute path of the winning variant file
 * @property {string[]} archived      — absolute paths of files moved into archive/
 * @property {string} archiveDir      — absolute path of the iteration-NNN-archive/ dir
 * @property {string} iteration       — 3-digit iteration string
 * @property {string} letter          — winning letter (lowercased)
 */
/**
 * @param {object} opts
 * @param {string} opts.mockupsDir — absolute path to <task-dir>/mockups
 * @param {string} opts.iteration  — 3-digit iteration string (e.g. "001")
 * @param {string} opts.letter     — winning letter (case-insensitive, single char)
 * @returns {PickResult}
 */
export function promoteVariant({ mockupsDir, iteration, letter }) {
    if (!mockupsDir || typeof mockupsDir !== 'string') {
        throw new Error('promoteVariant: mockupsDir is required');
    }
    if (!/^\d{3}$/.test(iteration)) {
        throw new Error(`promoteVariant: iteration must be a 3-digit string, got ${iteration}`);
    }
    if (typeof letter !== 'string' || !/^[a-z]$/i.test(letter)) {
        throw new Error(`promoteVariant: letter must be a single letter, got ${letter}`);
    }
    if (!existsSync(mockupsDir)) {
        throw new Error(`promoteVariant: mockups directory not found at ${mockupsDir}`);
    }
    const lower = letter.toLowerCase();
    const winnerFilename = `iteration-${iteration}-variant-${lower}.html`;
    const winnerPath = resolvePath(mockupsDir, winnerFilename);
    if (!existsSync(winnerPath)) {
        throw new Error(`promoteVariant: winning variant not found at ${winnerPath}. Run \`apt-tools variant-gallery <task-dir>\` to see what's available.`);
    }
    const promotedPath = resolvePath(mockupsDir, `iteration-${iteration}.html`);
    copyFileSync(winnerPath, promotedPath);
    const archiveDir = resolvePath(mockupsDir, `iteration-${iteration}-archive`);
    if (!existsSync(archiveDir))
        mkdirSync(archiveDir, { recursive: true });
    const entries = readdirSync(mockupsDir);
    const archived = [];
    for (const name of entries) {
        const variantMatch = name.match(VARIANT_RE);
        if (variantMatch && variantMatch[1] === iteration) {
            const dest = resolvePath(archiveDir, name);
            renameSync(resolvePath(mockupsDir, name), dest);
            archived.push(dest);
            continue;
        }
        const galleryMatch = name.match(GALLERY_RE);
        if (galleryMatch && galleryMatch[1] === iteration) {
            const dest = resolvePath(archiveDir, name);
            renameSync(resolvePath(mockupsDir, name), dest);
            archived.push(dest);
        }
    }
    // Append log if mockup_log.md exists — don't create one if absent,
    // that's the skill's authoring contract.
    const logPath = resolvePath(mockupsDir, 'mockup_log.md');
    if (existsSync(logPath)) {
        appendFileSync(logPath, [
            '',
            `## iteration-${iteration} — pick ${lower}`,
            `Winner: ${winnerFilename}`,
            `Promoted to: iteration-${iteration}.html`,
            `Archive: iteration-${iteration}-archive/`,
            `Picked: ${new Date().toISOString()}`,
            '',
        ].join('\n'), 'utf8');
    }
    return {
        promoted: promotedPath,
        source: winnerPath,
        archived,
        archiveDir,
        iteration,
        letter: lower,
    };
}
//# sourceMappingURL=pick.mjs.map