// engine/compliance-injector.ts — Automatic IEEE/ISO/GDPR compliance injection (SPEC-202)
//
// Loads compliance framework definitions from the 3-layer config system and
// injects relevant criteria into spec content based on context detection.
//
// Source: src/config/compliance-frameworks.json (system defaults)
// Override: data/global/compliance-frameworks-custom.json
//           data/projects/{hash}/config/compliance-frameworks-overrides.json
import { z } from 'zod';
import { ConfigLoader } from './config-loader.js';
// ---------------------------------------------------------------------------
// Schema
// ---------------------------------------------------------------------------
export const ComplianceFrameworkDefSchema = z.object({
    id: z.string().min(1).describe('Framework identifier (e.g. "gdpr", "iso-27001", "hipaa")'),
    name: z.string().min(1).describe('Short framework name (e.g. "GDPR", "ISO 27001")'),
    fullName: z.string().min(1).describe('Full framework name'),
    type: z
        .enum(['privacy', 'security', 'quality', 'testing', 'accessibility'])
        .describe('Framework type'),
    regions: z.array(z.string()).describe('Applicable regions or countries (use "global" for all)'),
    triggerKeywords: z
        .array(z.string())
        .describe('Keywords in spec/project content that suggest this framework applies'),
    dataTypes: z
        .array(z.string())
        .describe('Sensitive data types this framework covers (pii, financial, health, etc.)'),
    criteria: z
        .array(z.string())
        .min(1)
        .describe('Acceptance criteria to inject into specs when framework is detected'),
    references: z.array(z.string()).describe('Official documentation URLs'),
});
const frameworksArraySchema = z.array(ComplianceFrameworkDefSchema);
// ---------------------------------------------------------------------------
// Loader singleton
// ---------------------------------------------------------------------------
let _loader = null;
function getLoader() {
    _loader ??= new ConfigLoader('compliance-frameworks', frameworksArraySchema);
    return _loader;
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Load all compliance framework definitions from the 3-layer config system.
 */
export function loadComplianceFrameworkDefs(projectHash) {
    return getLoader().load(projectHash);
}
/**
 * Detect which compliance frameworks apply to the given context.
 *
 * A framework is applicable when ANY of its triggerKeywords appear in the
 * combined context string (spec description + project stack).
 */
export function detectApplicableFrameworks(context, projectHash) {
    const lower = context.toLowerCase();
    const all = loadComplianceFrameworkDefs(projectHash);
    return all.filter((fw) => fw.triggerKeywords.some((kw) => lower.includes(kw.toLowerCase())));
}
/**
 * Generate acceptance criteria to inject into a spec based on detected frameworks.
 * Deduplicates criteria across frameworks and caps at maxCriteria (default: 8).
 */
export function generateComplianceCriteria(context, projectHash, maxCriteria = 8) {
    const frameworks = detectApplicableFrameworks(context, projectHash);
    const seen = new Set();
    const result = [];
    for (const fw of frameworks) {
        for (const criterion of fw.criteria) {
            if (!seen.has(criterion) && result.length < maxCriteria) {
                seen.add(criterion);
                result.push(criterion);
            }
        }
    }
    return result;
}
/**
 * Build a markdown compliance section summarizing detected frameworks and their criteria.
 * Intended for injection into technical.md.
 */
export function buildComplianceSection(context, projectHash) {
    const frameworks = detectApplicableFrameworks(context, projectHash);
    if (frameworks.length === 0) {
        return '';
    }
    const lines = [
        '## Compliance Frameworks',
        '',
        '> **Note**: The following compliance frameworks were automatically detected based on project context.',
        '> Verify applicability with your legal/compliance team.',
        '',
    ];
    for (const fw of frameworks) {
        lines.push(`### ${fw.name} — ${fw.fullName}`);
        lines.push('');
        lines.push(`**Type**: ${fw.type} | **Regions**: ${fw.regions.join(', ')}`);
        lines.push('');
        lines.push('**Required criteria:**');
        lines.push('');
        for (const criterion of fw.criteria) {
            lines.push(`- [ ] ${criterion}`);
        }
        lines.push('');
        if (fw.references.length > 0) {
            lines.push(`**References**: ${fw.references.map((r) => `[${r}](${r})`).join(' | ')}`);
            lines.push('');
        }
    }
    return lines.join('\n');
}
/**
 * Get framework by ID. Returns undefined if not found.
 */
export function getFrameworkById(id, projectHash) {
    return loadComplianceFrameworkDefs(projectHash).find((fw) => fw.id === id);
}
//# sourceMappingURL=compliance-injector.js.map