// tools/data-governance/audit-handler.ts — privacy-notice and audit subcommands
import { specStore, knowledgeStore } from '../../storage/index.js';
import { ti } from '../../i18n/index.js';
import { detectPIIInSpec, detectLegalFramework, buildDefaultPrivacyConfig, } from '../../engine/pii-detector.js';
import { readFile } from 'node:fs/promises';
// ---------------------------------------------------------------------------
// privacy-notice subcommand
// ---------------------------------------------------------------------------
export async function handlePrivacyNotice(projectId) {
    const specs = await specStore.listSpecs(projectId);
    const privacyItems = [];
    for (const spec of specs) {
        let specText = `${spec.title} ${spec.type}`;
        try {
            if (spec.specPath) {
                specText += ' ' + (await readFile(spec.specPath, 'utf-8'));
            }
        }
        catch {
            /* file not available */
        }
        const result = detectPIIInSpec(spec.title, specText, specText);
        if (result.hasPII) {
            privacyItems.push({
                specId: spec.id,
                title: spec.title,
                piiFields: result.fields.map((f) => `${f.fieldName} (${f.category})`),
                legalBasis: result.recommendedLegalBasis,
            });
        }
    }
    const notice = buildPrivacyNoticeText(privacyItems);
    return {
        content: [
            {
                type: 'text',
                text: ti('tools.data_governance.privacyNoticeSuccess', {
                    count: String(privacyItems.length),
                }),
            },
            {
                type: 'text',
                text: JSON.stringify({
                    subcommand: 'privacy-notice',
                    specsWithPII: privacyItems.length,
                    totalSpecs: specs.length,
                    noticeText: notice,
                    disclaimer: 'This is a technical privacy notice draft. Legal review is required before publication.',
                }, null, 2),
            },
        ],
    };
}
// ---------------------------------------------------------------------------
// audit subcommand
// ---------------------------------------------------------------------------
export async function handleAudit(projectId) {
    const specs = await specStore.listSpecs(projectId);
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    const framework = detectLegalFramework({
        /* v8 ignore next -- knowledge.projectPath always present when knowledge exists; fallback is defensive */
        projectPath: knowledge?.projectPath ?? '',
        existingText: '',
    });
    const privacyConfig = buildDefaultPrivacyConfig(framework, []);
    const auditItems = [];
    for (const spec of specs) {
        let specText = `${spec.title} ${spec.type}`;
        try {
            if (spec.specPath) {
                specText += ' ' + (await readFile(spec.specPath, 'utf-8'));
            }
        }
        catch {
            /* file not available */
        }
        const result = detectPIIInSpec(spec.title, specText, specText);
        const hasPrivacySection = specText.toLowerCase().includes('privacidad y datos') ||
            specText.toLowerCase().includes('privacy') ||
            specText.toLowerCase().includes('gdpr');
        let complianceStatus = 'compliant';
        if (result.hasPII && !hasPrivacySection) {
            complianceStatus = 'missing-criteria';
        }
        else if (result.hasPII) {
            complianceStatus = 'needs-review';
        }
        auditItems.push({
            specId: spec.id,
            title: spec.title,
            hasPII: result.hasPII,
            piiFieldCount: result.fields.length,
            sensitiveSpecialCount: result.sensitiveSpecialCount,
            challengeRequired: result.hasPII,
            complianceStatus,
        });
    }
    const nonCompliant = auditItems.filter((i) => i.complianceStatus === 'missing-criteria').length;
    return {
        content: [
            {
                type: 'text',
                text: ti('tools.data_governance.auditSuccess', {
                    total: String(specs.length),
                    nonCompliant: String(nonCompliant),
                }),
            },
            {
                type: 'text',
                text: JSON.stringify({
                    subcommand: 'audit',
                    totalSpecs: specs.length,
                    specsWithPII: auditItems.filter((i) => i.hasPII).length,
                    nonCompliantSpecs: nonCompliant,
                    framework,
                    privacyConfig: {
                        defaultRetentionDays: privacyConfig.defaultRetentionDays,
                        auditRetentionDays: privacyConfig.auditRetentionDays,
                    },
                    items: auditItems,
                }, null, 2),
            },
        ],
    };
}
// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------
export function buildPrivacyNoticeText(items) {
    if (items.length === 0) {
        return 'No personal data processing detected in current specs.';
    }
    const lines = [
        '# Privacy Notice — Technical Draft',
        '',
        '> DISCLAIMER: This is a technical draft generated by Planu.',
        '> The legal team must review and approve before publication.',
        '',
        '## Data We Collect and Process',
        '',
    ];
    for (const item of items) {
        lines.push(`### ${item.title} (${item.specId})`);
        lines.push('');
        lines.push(`**Data collected**: ${item.piiFields.join(', ')}`);
        lines.push(`**Legal basis**: ${item.legalBasis}`);
        lines.push('');
    }
    lines.push('## Your Rights');
    lines.push('');
    lines.push('- Right to access your personal data');
    lines.push('- Right to rectification of inaccurate data');
    lines.push('- Right to erasure ("right to be forgotten")');
    lines.push('- Right to data portability');
    lines.push('- Right to object to processing');
    lines.push('');
    lines.push('## Contact');
    lines.push('');
    lines.push('Contact your Data Protection Officer (DPO) for privacy-related requests.');
    return lines.join('\n');
}
//# sourceMappingURL=audit-handler.js.map