/**
 * FDA SaMD Compliance Pack
 *
 * FDA Software as a Medical Device (SaMD) for AI/ML systems under
 * the Federal Food, Drug, and Cosmetic Act §201(h) and 21 CFR Parts
 * 807, 820, 821.
 *
 * Standards referenced:
 *   - 21 CFR Part 820 QMSR (Quality Management System Regulation,
 *     effective 2 February 2026; harmonises with ISO 13485:2016)
 *   - 2024 FDA PCCP Guidance (Predetermined Change Control Plan)
 *   - 2024 FDA AI/ML Lifecycle Guidance
 *   - Good Machine Learning Practice Principles (2021 FDA+HC+MHRA)
 *   - 21 CFR Part 803 (Medical Device Reporting / MDR)
 *   - 21 CFR Part 822 (Post-market surveillance)
 *   - PATCH Act §524B (2023 cybersecurity for premarket submissions)
 *   - IMDRF SaMD Risk Categorization Framework (Category I-IV)
 *   - 510(k), De Novo, PMA pathways
 *
 * Current state (2026):
 *   - QMSR effective 2 Feb 2026 -- new SaMD submissions must use
 *     QMSR (ISO 13485:2016 alignment).
 *   - PCCP accepted as formal mechanism for AI/ML model updates.
 *   - GMLP 10 principles are the de facto AI/ML SaMD baseline.
 *   - SBOM mandatory for cybersecurity (PATCH Act).
 *   - Real-world performance monitoring required per 2024 guidance.
 *
 * @connexum/ai-governance
 */
import { sharedPhiClassifier } from './_base-classifiers.js';
/**
 * FDA SaMD (Software as a Medical Device) category classifiers.
 * 21 CFR Parts 820 (QMSR) + 830 (UDI) + FDA AI/ML Action Plan.
 * PHI is BLOCK; clinical data and medical imaging are LOG (evidence capture).
 */
export const FDA_SAMD_CATEGORY_CLASSIFIERS = {
    PHI: {
        references: ['21 CFR 820 QMSR -- SaMD handling PHI; 45 CFR 164.312 applies when PHI is processed'],
        // 21 CFR 820 QMSR cross-references 45 CFR 164.312 when SaMD processes PHI.
        // sharedPhiClassifier implements the HIPAA 18 Safe Harbor identifiers.
        // SaMD-specific patient context markers are added for SaMD scope enforcement.
        classifier: (input) => {
            if (sharedPhiClassifier(input))
                return true;
            if (/\b(?:patient|subject\s+id)[:\s]+\d{6,12}\b/i.test(input))
                return true;
            return false;
        },
    },
    CLINICAL_DATA: {
        references: ['21 CFR Part 812 -- IDE; SaMD clinical evaluation data; IMDRF SAMD N41'],
        classifier: (input) => {
            if (/\b(?:clinical\s+(?:trial|study|data|evaluation)|IDE\s+(?:study|data)|post.?market\s+clinical)\b/i.test(input))
                return true;
            if (/\b(?:vital\s+signs|biomarker|lab\s+result|pathology\s+report|radiology\s+finding)\b/i.test(input))
                return true;
            return false;
        },
    },
    MEDICAL_IMAGING: {
        references: ['FDA AI/ML Action Plan -- medical imaging AI; SaMD intended purpose for imaging'],
        classifier: (input) => {
            if (/\b(?:DICOM|medical\s+(?:image|imaging|scan)|MRI|CT\s+scan|X.?ray|PET\s+scan|ultrasound\s+image)\b/i.test(input))
                return true;
            if (/\b(?:radiograph|mammogram|colonoscopy|retinal\s+(?:image|scan))\b/i.test(input))
                return true;
            return false;
        },
    },
    CREDENTIALS: {
        references: ['21 CFR Part 11 / QMSR -- access controls for SaMD systems'],
        classifier: (input) => {
            if (/\b(?:api[_-]?key|apikey)\s*[=:]\s*["']?[A-Za-z0-9_\-\/+]{16,}["']?/i.test(input))
                return true;
            if (/\bpassword\s*[=:]\s*["']?[A-Za-z0-9!@#$%^&*_\-]{8,}["']?/i.test(input))
                return true;
            if (/\bAKIA[A-Z0-9]{16}\b/.test(input))
                return true;
            if (/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/.test(input))
                return true;
            return false;
        },
    },
};
export const FDA_SAMD_PACK = {
    categoryClassifiers: FDA_SAMD_CATEGORY_CLASSIFIERS,
    /** P3.5: PHI and clinical data are inherently subject-keyed per FDA SaMD guidance and HIPAA intersection. */
    subjectKeyedCategories: ['PHI', 'CLINICAL_DATA'],
    id: 'fda-samd',
    name: 'FDA SaMD (AI/ML)',
    version: '1.0.0',
    contentHash: 'ec29b8f318a1b2347ac7b81296549279249e31e1ef710bb4477642ac9d89c564',
    description: 'FDA Software as a Medical Device for AI/ML under FD&C Act §201(h) + 21 CFR 807/820/821. Covers QMSR (effective Feb 2026), 2024 PCCP Guidance, 2024 AI/ML Lifecycle Guidance, GMLP Principles, 21 CFR 803 MDR, PATCH Act cybersecurity, IMDRF SaMD categorisation.',
    authority: 'US Food and Drug Administration (CDRH + CBER + CDER)',
    industries: ['medical-devices', 'digital-health', 'clinical-decision-support', 'diagnostic-ai', 'therapeutic-ai', 'radiology-ai', 'pathology-ai', 'remote-patient-monitoring', 'digital-therapeutics'],
    requiredModules: [
        {
            name: 'governance-runtime',
            required: true,
            reason: 'QMSR validation gate; IMDRF SaMD category tracking; GMLP principle evaluation',
            reference: '21 CFR 820 (QMSR); IMDRF SaMD; GMLP 2021',
        },
        {
            name: 'audit-integrity',
            required: true,
            reason: 'Device history records (DHR); 21 CFR Part 11 e-records overlap',
            reference: '21 CFR 820.184 DHR; 21 CFR 820.180 records',
        },
        {
            name: 'data-classifier',
            required: true,
            reason: 'PHI + clinical data + medical imaging classification; intended-use scope enforcement',
            reference: '21 CFR 801 labelling; HIPAA pairing',
        },
        {
            name: 'session-persistence',
            required: true,
            reason: 'Real-world performance monitoring continuity across sessions',
            reference: '2024 FDA AI/ML Lifecycle Guidance',
        },
        {
            name: 'supply-chain',
            required: true,
            reason: 'SBOM for PATCH Act cybersecurity; OEM / component / model provenance',
            reference: 'PATCH Act §524B (2023)',
        },
        {
            name: 'approval-queue',
            required: true,
            reason: 'PCCP boundary enforcement; non-PCCP changes routed to human review; MDR filing approval',
            reference: '2024 FDA PCCP Guidance; 21 CFR 803 MDR',
        },
        {
            name: 'attestation-manager',
            required: true,
            reason: 'Clinical validation attestations per IMDRF category; QMSR evidence; GMLP principle attestation; post-market surveillance plan',
            reference: '21 CFR 820 QMSR; 21 CFR 822 post-market',
        },
        {
            name: 'anomaly-detector',
            required: true,
            reason: 'Real-world performance drift detection; adverse event signal detection',
            reference: '2024 FDA AI/ML Lifecycle Guidance',
        },
        {
            name: 'bias-monitor',
            required: true,
            reason: 'Demographic subgroup performance tracking; 2024 AI/ML bias guidance',
            reference: '2024 FDA AI/ML Lifecycle Guidance (bias)',
        },
        {
            name: 'transparency-injector',
            required: true,
            reason: 'Indication for use disclosure; AI nature disclosure to clinicians / patients',
            reference: '21 CFR 801.109 physician labelling; FDA indication-for-use',
        },
        {
            name: 'event-bus',
            required: true,
            reason: 'MDR 30-day / 5-day reporting clocks; adverse event events',
            reference: '21 CFR 803',
        },
    ],
    moduleConfig: {
        'governance-runtime': {
            qmsrValidationRequired: true,
            imdrfCategoryTrackingRequired: true,
            gmlpPrincipleEvaluationRequired: true,
        },
        'approval-queue': {
            pccpBoundaryEnforcement: true,
            mdrFilingApprovalRequired: true,
            nonPccpChangeRequiresReview: true,
        },
        'attestation-manager': {
            clinicalValidationPerImdrfCategoryRequired: true,
            qmsrEvidenceRequired: true,
            gmlpPrincipleAttestationRequired: true,
            postMarketSurveillancePlanRequired: true,
        },
        'supply-chain': {
            sbomRequired: true,
            patchActAlignmentRequired: true,
        },
        'anomaly-detector': {
            realWorldPerformanceMonitoringRequired: true,
            adverseEventSignalDetectionActive: true,
        },
        'bias-monitor': {
            demographicSubgroupPerformanceRequired: true,
        },
        'event-bus': {
            mdrThirtyDayClockActive: true,
            mdrFiveDayCorrectiveActionClockActive: true,
        },
        'transparency-injector': {
            indicationForUseDisclosureRequired: true,
            aiNatureDisclosureRequired: true,
        },
    },
    providerPolicy: {
        blockedProviders: ['deepseek', 'baidu', 'alibaba'],
        requiredCapabilities: ['FDA-SAMD-READY', 'QMSR-ALIGNED'],
        blockReasons: {
            deepseek: 'PRC jurisdiction; cannot support QMSR supplier oversight or clinical-data protection.',
            baidu: 'PRC jurisdiction; clinical-data protection risk.',
            alibaba: 'PRC jurisdiction; clinical-data protection risk.',
        },
    },
    dataPolicy: {
        scanCategories: ['PHI', 'CLINICAL_DATA', 'MEDICAL_IMAGING', 'CREDENTIALS'],
        categoryActions: {
            PHI: 'BLOCK',
            CLINICAL_DATA: 'LOG',
            MEDICAL_IMAGING: 'LOG',
            CREDENTIALS: 'BLOCK',
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256-GCM',
        minimumClassification: 'RESTRICTED',
    },
    retentionPolicy: {
        sovereignty: ['US'],
        auditLogRetentionDays: 3650, // 10 years aligned with device-history-record lifecycle
        sessionRetentionDays: 730,
        incidentRetentionDays: 3650,
        reference: '21 CFR 820.184 DHR + 21 CFR 820.180 records (device lifetime + 2 years minimum; 10 years typical for SaMD)',
    },
    incidentPolicy: {
        notificationDeadlineHours: 720, // 30 days for MDR
        reference: '21 CFR 803 MDR: 30 days for death / serious injury / malfunction likely to cause death or serious injury. 5-day report for unplanned corrective actions to prevent substantial risk. Filed via FDA MAUDE.',
        requiredRecipients: ['fda-maude', 'quality-leadership', 'medical-affairs', 'risk-management'],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: 'samd-qmsr-validation',
            description: 'QMSR validation (IQ/OQ/PQ + design controls) attestation on file',
            reference: '21 CFR 820 (QMSR); 820.30',
            check: 'samd_qmsr_validation_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'samd-pccp',
            description: 'PCCP boundary enforcement for AI/ML model modifications',
            reference: '2024 FDA PCCP Guidance',
            check: 'samd_pccp_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'samd-sbom',
            description: 'SBOM on file per PATCH Act',
            reference: 'PATCH Act §524B',
            check: 'samd_sbom_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'samd-clinical-validation',
            description: 'Clinical validation per IMDRF SaMD category',
            reference: '2024 FDA AI/ML Lifecycle Guidance; IMDRF SaMD',
            check: 'samd_clinical_validation_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'samd-real-world-perf',
            description: 'Real-world performance monitoring active',
            reference: '2024 FDA AI/ML Lifecycle Guidance',
            check: 'samd_real_world_perf_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'samd-mdr',
            description: '21 CFR 803 MDR 30-day + 5-day clocks configured',
            reference: '21 CFR 803',
            check: 'samd_mdr_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'samd-post-market',
            description: 'Post-market surveillance plan on file',
            reference: '21 CFR 822; 2024 AI/ML Lifecycle Guidance',
            check: 'samd_post_market_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'samd-gmlp',
            description: 'GMLP 10-principle evaluation recorded',
            reference: 'GMLP Principles (2021 FDA+HC+MHRA)',
            check: 'samd_gmlp_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'samd-imdrf-category',
            description: 'IMDRF SaMD category (I-IV) tracked; risk-proportionate controls',
            reference: 'IMDRF SaMD Framework',
            check: 'samd_imdrf_category_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'samd-bias',
            description: 'Demographic subgroup performance monitored',
            reference: '2024 FDA AI/ML Lifecycle Guidance (bias)',
            check: 'samd_bias_active',
            failSeverity: 'MEDIUM',
        },
        {
            id: 'samd-intended-use',
            description: 'Indication for use + AI nature disclosed to clinicians/patients',
            reference: '21 CFR 801.109; FDA indication-for-use',
            check: 'samd_intended_use_active',
            failSeverity: 'HIGH',
        },
    ],
};
//# sourceMappingURL=fda-samd.js.map