// ---------------------------------------------------------------------------
// Keyword dictionaries
// ---------------------------------------------------------------------------
const DOMAIN_KEYWORDS = {
    fintech: [
        'stripe',
        'paypal',
        'braintree',
        'square',
        'adyen',
        'plaid',
        'dwolla',
        'wise',
        'mercadopago',
        'conekta',
        'openpay',
        'payment',
        'banking',
        'wallet',
        'crypto',
        'blockchain',
        'ledger',
        'kyc',
        'aml',
    ],
    health: [
        'fhir',
        'hl7',
        'medical',
        'health',
        'patient',
        'clinic',
        'hospital',
        'pharma',
        'hipaa',
        'ehr',
        'emr',
        'dicom',
        'telehealth',
        'telemedicine',
    ],
    billing: [
        'invoice',
        'billing',
        'tax',
        'vat',
        'subscription',
        'recurring',
        'checkout',
        'pricing',
        'plan',
        'coupon',
        'refund',
        'chargeback',
    ],
    ecommerce: [
        'ecommerce',
        'e-commerce',
        'shopify',
        'woocommerce',
        'magento',
        'prestashop',
        'cart',
        'catalog',
        'product',
        'storefront',
        'marketplace',
        'medusa',
        'saleor',
        'vendure',
    ],
    'ai-ml': [
        'openai',
        'langchain',
        'llm',
        'gpt',
        'claude',
        'anthropic',
        'huggingface',
        'tensorflow',
        'pytorch',
        'scikit',
        'ml',
        'machine-learning',
        'inference',
        'embedding',
        'vector',
        'rag',
        'fine-tune',
        'model-training',
    ],
    social: [
        'socket.io',
        'chat',
        'social',
        'messaging',
        'feed',
        'timeline',
        'friend',
        'follower',
        'community',
        'forum',
        'comment',
        'reaction',
        'notification',
        'real-time',
    ],
    gaming: [
        'unity',
        'godot',
        'unreal',
        'game',
        'gaming',
        'player',
        'leaderboard',
        'match',
        'lobby',
        'multiplayer',
        'phaser',
        'pixi',
        'three.js',
    ],
    education: [
        'lms',
        'course',
        'student',
        'teacher',
        'school',
        'university',
        'classroom',
        'quiz',
        'exam',
        'grade',
        'enrollment',
        'moodle',
        'canvas',
        'edtech',
    ],
    iot: [
        'mqtt',
        'iot',
        'sensor',
        'device',
        'firmware',
        'embedded',
        'arduino',
        'raspberry',
        'zigbee',
        'z-wave',
        'home-assistant',
        'smart-home',
    ],
    hr: [
        'hr',
        'employee',
        'payroll',
        'recruitment',
        'hiring',
        'onboarding',
        'timesheet',
        'attendance',
        'performance-review',
        'workforce',
    ],
    'real-estate': [
        'property',
        'real-estate',
        'realestate',
        'listing',
        'tenant',
        'landlord',
        'mortgage',
        'mls',
        'zillow',
        'rental',
    ],
    logistics: [
        'logistics',
        'shipping',
        'delivery',
        'warehouse',
        'inventory',
        'tracking',
        'fleet',
        'route',
        'freight',
        'supply-chain',
        'fulfillment',
    ],
    media: [
        'media',
        'streaming',
        'video',
        'audio',
        'podcast',
        'cms',
        'content',
        'publishing',
        'editorial',
        'drm',
        'copyright',
    ],
    government: [
        'government',
        'gov',
        'citizen',
        'municipal',
        'public-sector',
        'e-gov',
        'permit',
        'license',
        'compliance',
        'regulation',
        'fedramp',
    ],
};
const COUNTRY_HINTS = {
    // Currencies
    MXN: ['MX'],
    USD: ['US'],
    COP: ['CO'],
    ARS: ['AR'],
    BRL: ['BR'],
    EUR: ['DE', 'FR', 'ES', 'IT'],
    GBP: ['GB'],
    CAD: ['CA'],
    JPY: ['JP'],
    INR: ['IN'],
    AUD: ['AU'],
    CLP: ['CL'],
    PEN: ['PE'],
    // Timezones (partial matches)
    'America/Mexico': ['MX'],
    'America/Bogota': ['CO'],
    'America/Argentina': ['AR'],
    'America/Sao_Paulo': ['BR'],
    'America/New_York': ['US'],
    'America/Chicago': ['US'],
    'America/Los_Angeles': ['US'],
    'America/Toronto': ['CA'],
    'Europe/London': ['GB'],
    'Europe/Berlin': ['DE'],
    'Europe/Paris': ['FR'],
    'Europe/Madrid': ['ES'],
    'Asia/Tokyo': ['JP'],
    'Asia/Kolkata': ['IN'],
    // Locale prefixes
    'es-MX': ['MX'],
    'es-CO': ['CO'],
    'es-AR': ['AR'],
    'es-CL': ['CL'],
    'es-PE': ['PE'],
    'en-US': ['US'],
    'en-GB': ['GB'],
    'pt-BR': ['BR'],
    'fr-FR': ['FR'],
    'de-DE': ['DE'],
    'ja-JP': ['JP'],
};
const MINOR_KEYWORDS = [
    'child',
    'children',
    'minor',
    'kid',
    'teen',
    'youth',
    'coppa',
    'age-gate',
    'parental',
    'school',
    'student',
];
const HEALTH_KEYWORDS = [
    'patient',
    'medical',
    'health',
    'hipaa',
    'clinical',
    'diagnosis',
    'prescription',
    'ehr',
    'emr',
    'telehealth',
];
const AUTH_KEYWORDS = [
    'auth',
    'login',
    'signup',
    'register',
    'session',
    'jwt',
    'oauth',
    'passport',
    'next-auth',
    'clerk',
    'supabase',
    'firebase',
];
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Normalize a string for keyword matching (lowercase, trim) */
function normalize(s) {
    return s.toLowerCase().trim();
}
/** Build a flat searchable corpus from ProjectKnowledge.
 *  Defensive against partial data — callers may pass incomplete objects (e.g., tests with `as never`). */
function buildCorpus(knowledge) {
    /* eslint-disable @typescript-eslint/no-unnecessary-condition */
    const parts = [
        knowledge.language ?? '',
        knowledge.framework ?? '',
        knowledge.orm ?? '',
        knowledge.database ?? '',
        knowledge.packageManager ?? '',
        ...(knowledge.stack ?? []),
        ...(knowledge.externalServices ?? []),
        ...(knowledge.layers ?? []),
        ...Object.keys(knowledge.conventions ?? {}),
        ...Object.values(knowledge.conventions ?? {}),
        ...Object.keys(knowledge.tooling ?? {}),
        ...Object.values(knowledge.tooling ?? {}),
        ...(knowledge.apiContracts ?? []).map((c) => `${c.type} ${c.endpoints.join(' ')}`),
        ...(knowledge.apps ?? []).flatMap((a) => [
            a.name,
            a.type,
            a.language,
            a.framework ?? '',
            a.orm ?? '',
        ]),
    ];
    /* eslint-enable @typescript-eslint/no-unnecessary-condition */
    return normalize(parts.join(' '));
}
/** Check if corpus contains any keyword from list */
function matchesAny(corpus, keywords) {
    return keywords.some((kw) => corpus.includes(normalize(kw)));
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Detect which legal domains apply to a project based on its knowledge.
 * Always includes 'universal'.
 */
export function detectLegalDomains(knowledge) {
    const corpus = buildCorpus(knowledge);
    const domains = ['universal'];
    for (const [domain, keywords] of Object.entries(DOMAIN_KEYWORDS)) {
        if (matchesAny(corpus, keywords)) {
            domains.push(domain);
        }
    }
    return domains;
}
/**
 * Detect target countries from locale, currency, timezone, and i18n hints.
 * Returns ISO country codes. Empty array if nothing detected.
 */
export function detectCountries(knowledge) {
    const corpus = buildCorpus(knowledge);
    const countries = new Set();
    // Check locale field directly
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    const localeUpper = (knowledge.locale ?? '').toUpperCase();
    for (const [hint, codes] of Object.entries(COUNTRY_HINTS)) {
        if (localeUpper.includes(hint.toUpperCase())) {
            for (const code of codes) {
                countries.add(code);
            }
        }
    }
    // Scan corpus for currency, timezone, and locale patterns
    for (const [hint, codes] of Object.entries(COUNTRY_HINTS)) {
        if (corpus.includes(normalize(hint))) {
            for (const code of codes) {
                countries.add(code);
            }
        }
    }
    return [...countries];
}
/**
 * Detect audience characteristics (minors, patients, B2B/B2C, employees).
 */
export function detectAudience(knowledge) {
    const corpus = buildCorpus(knowledge);
    const domains = detectLegalDomains(knowledge);
    const includesMinors = matchesAny(corpus, MINOR_KEYWORDS) ||
        domains.includes('education') ||
        (domains.includes('gaming') && matchesAny(corpus, MINOR_KEYWORDS)) ||
        (domains.includes('social') && matchesAny(corpus, ['age-gate', 'parental', 'coppa']));
    const includesPatients = matchesAny(corpus, HEALTH_KEYWORDS) || domains.includes('health');
    const includesEmployees = domains.includes('hr');
    // B2B heuristic: admin panels, dashboards, SaaS indicators
    const b2bKeywords = [
        'admin',
        'dashboard',
        'saas',
        'tenant',
        'organization',
        'workspace',
        'enterprise',
        'b2b',
        'crm',
        'erp',
    ];
    const isB2B = matchesAny(corpus, b2bKeywords);
    // B2C heuristic: public-facing user apps
    const b2cKeywords = [
        'user',
        'signup',
        'register',
        'profile',
        'cart',
        'wishlist',
        'b2c',
        'consumer',
        'customer',
    ];
    const isB2C = matchesAny(corpus, b2cKeywords);
    return { includesMinors, includesPatients, includesEmployees, isB2B, isB2C };
}
/**
 * Detect types of sensitive data the project likely handles.
 */
export function detectDataTypes(knowledge) {
    const corpus = buildCorpus(knowledge);
    const domains = detectLegalDomains(knowledge);
    const types = new Set();
    // PII — almost any app with user models
    const piiKeywords = ['user', 'email', 'name', 'address', 'phone', 'profile', 'account'];
    if (matchesAny(corpus, piiKeywords)) {
        types.add('pii');
    }
    // Credentials — auth-based apps
    if (matchesAny(corpus, AUTH_KEYWORDS)) {
        types.add('credentials');
    }
    // Financial data
    if (domains.includes('fintech') || domains.includes('billing') || domains.includes('ecommerce')) {
        types.add('financial');
    }
    const financialKeywords = ['payment', 'card', 'bank', 'transaction', 'balance'];
    if (matchesAny(corpus, financialKeywords)) {
        types.add('financial');
    }
    // Health data
    if (domains.includes('health') || matchesAny(corpus, HEALTH_KEYWORDS)) {
        types.add('health');
    }
    // Children data
    if (matchesAny(corpus, MINOR_KEYWORDS) || domains.includes('education')) {
        types.add('children');
    }
    // Location data
    const locationKeywords = [
        'location',
        'gps',
        'geolocation',
        'latitude',
        'longitude',
        'map',
        'geofence',
        'tracking',
    ];
    if (matchesAny(corpus, locationKeywords)) {
        types.add('location');
    }
    // Biometric data
    const biometricKeywords = [
        'biometric',
        'fingerprint',
        'face-id',
        'faceid',
        'retina',
        'voice-print',
        'facial-recognition',
    ];
    if (matchesAny(corpus, biometricKeywords)) {
        types.add('biometric');
    }
    // Behavioral data
    const behavioralKeywords = [
        'analytics',
        'tracking',
        'behavior',
        'activity',
        'session-recording',
        'heatmap',
        'mixpanel',
        'amplitude',
        'segment',
    ];
    if (matchesAny(corpus, behavioralKeywords)) {
        types.add('behavioral');
    }
    return [...types];
}
/**
 * Build a complete LegalProfile by combining all detectors.
 * This is the main entry point called by init_project.
 */
export function buildLegalProfile(knowledge) {
    return {
        domains: detectLegalDomains(knowledge),
        countries: detectCountries(knowledge),
        audience: detectAudience(knowledge),
        dataTypes: detectDataTypes(knowledge),
        detectedAt: new Date().toISOString(),
        cachedRequirements: null,
        lastRefreshedAt: null,
    };
}
//# sourceMappingURL=detector.js.map