/**
 * Origin-file actions: accept, reject, ignore. Pure synchronous functions
 * over node:fs. No UI, no prompts, no logging. Each function is idempotent
 * on missing `.origin` (returns `noop`). On POSIX `accept` is atomic via
 * fs.renameSync; on Windows it falls back to unlink + rename with a
 * documented non-atomic window.
 */
import * as fs from 'node:fs';
import path from 'node:path';
import { toOriginPath } from './origin-file.js';
const IGNORED_MARKERS = {
    '.graphql': '# ignored file',
    '.htm': '<!-- ignored file -->',
    '.html': '<!-- ignored file -->',
};
const DEFAULT_IGNORED_MARKER = '// ignored file';
function getIgnoredMarker(filePath) {
    const ext = path.extname(filePath).toLowerCase();
    return IGNORED_MARKERS[ext] ?? DEFAULT_IGNORED_MARKER;
}
export function acceptOrigin(currentPath) {
    const originPath = toOriginPath(currentPath);
    if (!fs.existsSync(originPath)) {
        return { path: currentPath, reason: 'no origin file', status: 'noop' };
    }
    try {
        fs.renameSync(originPath, currentPath);
    }
    catch (error) {
        const { code } = error;
        if (process.platform === 'win32' && code === 'EEXIST') {
            // Windows: rename refuses to overwrite. Unlink then rename.
            // Non-atomic window: between unlink and rename, currentPath does
            // not exist. Acceptable trade-off — Windows is not a primary
            // contributor platform for this CLI.
            fs.unlinkSync(currentPath);
            fs.renameSync(originPath, currentPath);
        }
        else {
            throw error;
        }
    }
    return { path: currentPath, status: 'applied' };
}
export function rejectOrigin(currentPath) {
    const originPath = toOriginPath(currentPath);
    if (!fs.existsSync(originPath)) {
        return { path: currentPath, reason: 'no origin file', status: 'noop' };
    }
    fs.unlinkSync(originPath);
    return { path: currentPath, status: 'applied' };
}
export function ignoreOrigin(currentPath) {
    const originPath = toOriginPath(currentPath);
    if (!fs.existsSync(originPath)) {
        return { path: currentPath, reason: 'no origin file', status: 'noop' };
    }
    const marker = getIgnoredMarker(currentPath);
    const current = fs.readFileSync(currentPath, 'utf8');
    if (!current.startsWith(marker)) {
        const tmpPath = `${currentPath}.aurora-ignore.tmp`;
        fs.writeFileSync(tmpPath, `${marker}\n${current}`, 'utf8');
        fs.renameSync(tmpPath, currentPath);
    }
    fs.unlinkSync(originPath);
    return { path: currentPath, status: 'applied' };
}
