"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.emitGithubInlineArchitectureAnnotations = emitGithubInlineArchitectureAnnotations;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
function escapeAnnotationProperty(value) {
    return value
        .replaceAll('%', '%25')
        .replaceAll('\r', '%0D')
        .replaceAll('\n', '%0A')
        .replaceAll(':', '%3A')
        .replaceAll(',', '%2C');
}
function escapeAnnotationMessage(value) {
    return value
        .replaceAll('%', '%25')
        .replaceAll('\r', '%0D')
        .replaceAll('\n', '%0A');
}
function normalizeAnnotationPath(workspaceRoot, sourceFile) {
    if (!sourceFile || sourceFile.trim().length === 0) {
        return undefined;
    }
    const normalized = sourceFile.replace(/\\/g, '/');
    if (!path.isAbsolute(sourceFile)) {
        return normalized;
    }
    const relative = path.relative(workspaceRoot, sourceFile).replace(/\\/g, '/');
    if (relative.startsWith('..') || path.isAbsolute(relative)) {
        return undefined;
    }
    return relative;
}
function toAnnotatableFinding(workspaceRoot, finding) {
    if (typeof finding.id !== 'string' || !finding.id.startsWith('AP-DEP-')) {
        return undefined;
    }
    if (finding.severity !== 'error' &&
        finding.severity !== 'warning') {
        return undefined;
    }
    if (typeof finding.title !== 'string' || typeof finding.message !== 'string') {
        return undefined;
    }
    if (typeof finding.sourceFile !== 'string') {
        return undefined;
    }
    const file = normalizeAnnotationPath(workspaceRoot, finding.sourceFile);
    if (!file) {
        return undefined;
    }
    if (typeof finding.sourceLine !== 'number' || !Number.isFinite(finding.sourceLine)) {
        return undefined;
    }
    const line = Math.max(1, Math.floor(finding.sourceLine));
    const column = typeof finding.sourceColumn === 'number' && Number.isFinite(finding.sourceColumn)
        ? Math.max(1, Math.floor(finding.sourceColumn))
        : undefined;
    return {
        id: finding.id,
        title: finding.title,
        message: finding.message,
        severity: finding.severity,
        file,
        line,
        ...(column !== undefined ? { column } : {}),
    };
}
function emitGithubAnnotation(input) {
    const properties = [
        `file=${escapeAnnotationProperty(input.file)}`,
        `line=${input.line}`,
        ...(input.column !== undefined ? [`col=${input.column}`] : []),
        `title=${escapeAnnotationProperty(input.title)}`,
    ].join(',');
    const annotation = `::${input.level} ${properties}::${escapeAnnotationMessage(input.message)}`;
    console.log(annotation);
}
function formatUtcDate(date) {
    return date.toISOString().replace('T', ' ').replace('.000Z', 'Z');
}
function readMaxArtifactAgeMinutes() {
    const raw = process.env.ARCHPILOT_INLINE_ARTIFACT_MAX_AGE_MINUTES;
    if (!raw) {
        return 120;
    }
    const parsed = Number(raw);
    if (!Number.isFinite(parsed) || parsed <= 0) {
        return 120;
    }
    return Math.floor(parsed);
}
async function isFreshArtifact(filePath, maxAgeMinutes) {
    try {
        const stats = await node_fs_1.promises.stat(filePath);
        const ageMs = Date.now() - stats.mtime.getTime();
        return ageMs >= 0 && ageMs <= maxAgeMinutes * 60 * 1000;
    }
    catch {
        return false;
    }
}
async function loadFromValidationStatus(workspaceRoot, maxAgeMinutes) {
    const statusPath = path.join(workspaceRoot, '.archpilot', 'validation-status.json');
    let raw;
    try {
        raw = await node_fs_1.promises.readFile(statusPath, { encoding: 'utf8' });
    }
    catch (error) {
        if (error.code !== 'ENOENT') {
            console.log('ArchPilot inline annotations: unable to read validation-status.json.');
        }
        return undefined;
    }
    if (!(await isFreshArtifact(statusPath, maxAgeMinutes))) {
        console.log(`ArchPilot inline annotations: validation-status.json is stale (older than ${maxAgeMinutes} minutes).`);
        return undefined;
    }
    let parsed;
    try {
        parsed = JSON.parse(raw);
    }
    catch {
        console.log('ArchPilot inline annotations: validation-status.json is invalid JSON.');
        return undefined;
    }
    const results = Array.isArray(parsed.results) ? parsed.results : [];
    const findings = [];
    for (const result of results) {
        if (!result || typeof result !== 'object') {
            continue;
        }
        const typed = result;
        if (typed.passed !== false) {
            continue;
        }
        findings.push({
            id: typed.id,
            title: typed.title,
            severity: typed.severity,
            message: typed.message,
            sourceFile: typed.sourceFile,
            sourceLine: typed.sourceLine,
            sourceColumn: typed.sourceColumn,
        });
    }
    return {
        sourceLabel: '.archpilot/validation-status.json',
        findings,
    };
}
async function loadFromSummaryReport(workspaceRoot, maxAgeMinutes) {
    const summaryPath = path.join(workspaceRoot, '.archpilot', 'reports', 'architecture-summary.json');
    let raw;
    try {
        raw = await node_fs_1.promises.readFile(summaryPath, { encoding: 'utf8' });
    }
    catch (error) {
        if (error.code !== 'ENOENT') {
            console.log('ArchPilot inline annotations: unable to read architecture-summary.json.');
        }
        return undefined;
    }
    if (!(await isFreshArtifact(summaryPath, maxAgeMinutes))) {
        console.log(`ArchPilot inline annotations: architecture-summary.json is stale (older than ${maxAgeMinutes} minutes).`);
        return undefined;
    }
    let parsed;
    try {
        parsed = JSON.parse(raw);
    }
    catch {
        console.log('ArchPilot inline annotations: architecture-summary.json is invalid JSON.');
        return undefined;
    }
    const findings = Array.isArray(parsed.findings) ? parsed.findings : [];
    return {
        sourceLabel: '.archpilot/reports/architecture-summary.json',
        findings: findings.filter((entry) => !!entry && typeof entry === 'object'),
    };
}
async function emitGithubInlineArchitectureAnnotations(workspaceRoot) {
    const maxAgeMinutes = readMaxArtifactAgeMinutes();
    const loaded = (await loadFromValidationStatus(workspaceRoot, maxAgeMinutes)) ??
        (await loadFromSummaryReport(workspaceRoot, maxAgeMinutes));
    if (!loaded) {
        const now = formatUtcDate(new Date());
        console.log(`ArchPilot inline annotations: no fresh validation findings were found at ${now} UTC. Inline annotations were skipped to avoid stale output.`);
        return { reportFound: false, annotatedCount: 0, summaryOnlyCount: 0 };
    }
    let annotatedCount = 0;
    let summaryOnlyCount = 0;
    for (const finding of loaded.findings) {
        const annotatable = toAnnotatableFinding(workspaceRoot, finding);
        if (!annotatable) {
            summaryOnlyCount += 1;
            continue;
        }
        emitGithubAnnotation({
            level: annotatable.severity,
            file: annotatable.file,
            line: annotatable.line,
            ...(annotatable.column !== undefined ? { column: annotatable.column } : {}),
            title: `${annotatable.id} ${annotatable.title}`,
            message: annotatable.message,
        });
        annotatedCount += 1;
    }
    console.log(`ArchPilot inline annotations: ${annotatedCount} emitted, ${summaryOnlyCount} summary-only findings (source: ${loaded.sourceLabel}).`);
    return { reportFound: true, annotatedCount, summaryOnlyCount };
}
//# sourceMappingURL=githubInlineAnnotations.js.map