import fs from 'fs/promises';
import path from 'path';
import { NEXUS_PLG_EVENT_TYPES, NEXUS_PRIME_COAUTHOR_TRAILER, NEXUS_PRIME_PRESENCE_END, NEXUS_PRIME_PRESENCE_START, NEXUS_PRIME_WEBSITE, } from './nexus-signature.js';
async function readOptional(filePath) {
    if (!filePath)
        return null;
    try {
        return await fs.readFile(filePath, 'utf8');
    }
    catch {
        return null;
    }
}
function addCheck(checks, id, label, status, detail, evidence) {
    checks.push({ id, label, status, detail, evidence });
}
function hasPresenceBlock(value) {
    return value.includes(NEXUS_PRIME_PRESENCE_START) && value.includes(NEXUS_PRIME_PRESENCE_END);
}
export async function verifyNexusProof(options = {}) {
    const repoRoot = options.repoRoot ?? process.cwd();
    const checks = [];
    const prTemplatePath = path.join(repoRoot, '.github', 'pull_request_template.md');
    const readmePath = path.join(repoRoot, 'README.md');
    const telemetryPath = path.join(repoRoot, 'src', 'engines', 'telemetry-remote.ts');
    addCheck(checks, 'website.identity', 'Website identity', NEXUS_PRIME_WEBSITE === 'https://nexus-prime.cfd/' ? 'pass' : 'fail', `Expected canonical website https://nexus-prime.cfd/, got ${NEXUS_PRIME_WEBSITE}`, NEXUS_PRIME_WEBSITE);
    const prTemplate = await readOptional(prTemplatePath);
    if (!prTemplate) {
        addCheck(checks, 'pr.template', 'PR template presence', 'warn', 'No .github/pull_request_template.md found.');
    }
    else {
        const ok = hasPresenceBlock(prTemplate) && prTemplate.includes(NEXUS_PRIME_WEBSITE);
        addCheck(checks, 'pr.template', 'PR template presence', ok ? 'pass' : 'fail', ok
            ? 'Pull request template contains Nexus Prime Presence and website identity.'
            : 'Pull request template must include Nexus Prime Presence markers and website identity.', prTemplatePath);
    }
    const readme = await readOptional(readmePath);
    if (!readme) {
        addCheck(checks, 'docs.provenance', 'README provenance copy', 'warn', 'No README.md found.');
    }
    else {
        const ok = readme.includes('Provenance and social proof')
            && readme.includes('Nexus Prime Presence')
            && readme.includes('privacy-safe PLG events')
            && readme.includes(NEXUS_PRIME_WEBSITE);
        addCheck(checks, 'docs.provenance', 'README provenance copy', ok ? 'pass' : 'fail', ok
            ? 'README explains Nexus Prime signatures, attribution, telemetry, and social proof.'
            : 'README must explain Nexus Prime Presence, attribution, privacy-safe PLG events, and the website.', readmePath);
    }
    const telemetry = await readOptional(telemetryPath);
    if (!telemetry) {
        addCheck(checks, 'telemetry.redaction', 'Telemetry redaction guard', 'warn', 'Telemetry source was not found.');
    }
    else {
        const redactionPattern = String.raw `prompt|content|code|path|repo|branch|secret|token|file`;
        const hasRedaction = telemetry.includes(redactionPattern)
            && telemetry.includes('sanitizeEventData')
            && telemetry.includes('trackProductEvent');
        addCheck(checks, 'telemetry.redaction', 'Telemetry redaction guard', hasRedaction ? 'pass' : 'fail', hasRedaction
            ? 'Proof telemetry is routed through the sanitizer and blocks sensitive key classes.'
            : 'Proof telemetry must keep using sanitizeEventData and block prompt/code/path/repo/branch/secret/token/file keys.', telemetryPath);
    }
    const prBody = await readOptional(options.prBodyPath);
    if (options.prBodyPath) {
        const ok = Boolean(prBody && hasPresenceBlock(prBody) && prBody.includes(NEXUS_PRIME_WEBSITE));
        addCheck(checks, 'pr.body', 'PR body proof', ok ? 'pass' : 'fail', ok ? 'PR body contains Nexus Prime Presence.' : 'PR body is missing Nexus Prime Presence.', options.prBodyPath);
    }
    else {
        addCheck(checks, 'pr.body', 'PR body proof', 'warn', 'No PR body path supplied; skipping generated PR body verification.');
    }
    const commitMessage = await readOptional(options.commitMessagePath);
    if (options.commitMessagePath) {
        const ok = Boolean(commitMessage && commitMessage.includes(NEXUS_PRIME_COAUTHOR_TRAILER));
        addCheck(checks, 'commit.coauthor', 'Generated commit co-author trailer', ok ? 'pass' : 'fail', ok ? 'Commit message contains the Nexus Prime co-author trailer.' : 'Generated commit message is missing the Nexus Prime co-author trailer.', options.commitMessagePath);
    }
    else {
        addCheck(checks, 'commit.coauthor', 'Generated commit co-author trailer', 'warn', 'No commit message path supplied; skipping generated commit verification.');
    }
    const artifactPaths = options.artifactPaths ?? [];
    if (artifactPaths.length === 0) {
        addCheck(checks, 'artifact.signature', 'Generated artifact signatures', 'warn', 'No artifact paths supplied; skipping artifact signature verification.');
    }
    else {
        for (const artifactPath of artifactPaths) {
            const artifact = await readOptional(artifactPath);
            const ok = Boolean(artifact && artifact.includes('signed by Nexus Prime') && artifact.includes(NEXUS_PRIME_WEBSITE));
            addCheck(checks, `artifact.signature:${path.basename(artifactPath)}`, 'Generated artifact signature', ok ? 'pass' : 'fail', ok ? 'Artifact contains a Nexus Prime document signature.' : 'Artifact is missing a Nexus Prime document signature.', artifactPath);
        }
    }
    const passed = checks.filter((check) => check.status === 'pass').length;
    const warnings = checks.filter((check) => check.status === 'warn').length;
    const failed = checks.filter((check) => check.status === 'fail').length;
    const status = failed > 0 ? 'failed' : warnings > 0 ? 'attention' : 'verified';
    return {
        generatedAt: Date.now(),
        website: NEXUS_PRIME_WEBSITE,
        status,
        passed,
        warnings,
        failed,
        checks,
        proofEvents: NEXUS_PLG_EVENT_TYPES,
    };
}
export function formatNexusProofReport(summary) {
    const lines = [
        'Nexus Prime proof verification',
        `Website: ${summary.website}`,
        `Status: ${summary.status}`,
        `Checks: ${summary.passed} passed, ${summary.warnings} warning(s), ${summary.failed} failed`,
        '',
    ];
    for (const check of summary.checks) {
        const marker = check.status === 'pass' ? 'PASS' : check.status === 'warn' ? 'WARN' : 'FAIL';
        lines.push(`[${marker}] ${check.label}: ${check.detail}`);
    }
    return lines.join('\n');
}
