import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { createHash } from 'crypto';
/**
 * Captures apply_patch payload regressions into a golden samples structure.
 *
 * Trigger: apply_patch validation failure OR fixer failure
 * Condition: non-context errors only (format/json/prefix/etc.)
 *
 * Default destination:
 *   ~/.routecodex/errorsamples/apply_patch/<error-type>/
 *
 * Optional repo destination (explicit opt-in):
 *   ROUTECODEX_APPLY_PATCH_REGRESSION_TO_REPO=1
 *   → <repoRoot>/samples/ci-goldens/_regressions/apply_patch/<error-type>/
 *
 * Explicit override:
 *   ROUTECODEX_APPLY_PATCH_REGRESSION_DIR=/abs/path
 */
const MAX_SAMPLES_PER_TYPE = 250;
function detectRepoRootFromCwd() {
    try {
        let dir = process.cwd();
        for (let i = 0; i < 12; i += 1) {
            const marker = path.join(dir, 'samples', 'ci-goldens');
            const pkg = path.join(dir, 'package.json');
            if (fs.existsSync(marker) && fs.existsSync(pkg)) {
                try {
                    const raw = fs.readFileSync(pkg, 'utf-8');
                    const json = JSON.parse(raw);
                    if (json && typeof json === 'object' && String(json.name || '') === 'routecodex') {
                        return dir;
                    }
                }
                catch {
                    // ignore parse errors
                }
            }
            const parent = path.dirname(dir);
            if (parent === dir)
                break;
            dir = parent;
        }
    }
    catch {
        // ignore
    }
    return null;
}
function resolveSamplesRoot() {
    const explicit = String(process?.env?.ROUTECODEX_APPLY_PATCH_REGRESSION_DIR || '').trim();
    if (explicit) {
        return path.resolve(explicit);
    }
    const toRepo = String(process?.env?.ROUTECODEX_APPLY_PATCH_REGRESSION_TO_REPO || '').trim() === '1';
    if (toRepo) {
        const repoRoot = detectRepoRootFromCwd();
        if (repoRoot) {
            return path.join(repoRoot, 'samples', 'ci-goldens', '_regressions', 'apply_patch');
        }
    }
    return path.join(os.homedir(), '.routecodex', 'errorsamples', 'apply_patch');
}
function isContextError(error) {
    if (!error)
        return false;
    const lower = error.toLowerCase();
    return (lower.includes('failed to find context') ||
        lower.includes('failed to find expected lines') ||
        lower.includes('file not found') ||
        lower.includes('no such file'));
}
function stableSampleId(sample) {
    const mode = String(sample.meta?.applyPatchToolMode || '').trim();
    const key = `${String(sample.errorType || 'unknown')}:${String(sample.originalArgs ?? '')}:` +
        `${String(sample.normalizedArgs ?? '')}:${String(sample.fixerResult ?? '')}:${String(sample.validationError ?? '')}:${mode}`;
    return createHash('sha1').update(key).digest('hex').slice(0, 16);
}
export function captureApplyPatchRegression(sample) {
    try {
        if (isContextError(sample.validationError))
            return;
        const root = resolveSamplesRoot();
        const safeType = String(sample.errorType || 'unknown').replace(/[^a-z0-9-]/gi, '_');
        const typeDir = path.join(root, safeType);
        if (!fs.existsSync(typeDir)) {
            fs.mkdirSync(typeDir, { recursive: true });
        }
        // Check limit (best-effort; keep runtime safe)
        try {
            const existing = fs.readdirSync(typeDir).filter((f) => f.endsWith('.json'));
            if (existing.length >= MAX_SAMPLES_PER_TYPE)
                return;
        }
        catch {
            // ignore
        }
        const id = `sample_${stableSampleId(sample)}`;
        const file = path.join(typeDir, `${id}.json`);
        if (fs.existsSync(file))
            return;
        const fullSample = {
            id,
            timestamp: new Date().toISOString(),
            ...sample
        };
        fs.writeFileSync(file, JSON.stringify(fullSample, null, 2), 'utf-8');
    }
    catch {
        // Silently fail to avoid disrupting runtime
    }
}
