/**
 * NHS Data Security and Protection Toolkit (DSPT) Compliance Pack
 *
 * Regulation:
 *   NHS England / NHS Digital — Data Security and Protection Toolkit
 *   National Data Guardian (NDG) ten data security standards
 *   NHS Digital Care Records Service operating model
 *   Caldicott Principles (eight, 2020 revision)
 *   Common Law Duty of Confidentiality (clinical record context)
 *
 * Jurisdiction: GB — England (devolved equivalents Scotland / Wales /
 *   Northern Ireland have parallel toolkits but DSPT is the England standard
 *   used as the de-facto UK NHS baseline by suppliers).
 *
 * Regulator: NHS England (DSPT submission portal; assertion-based
 *   self-assessment with mandatory third-party assurance for "Standards Met"
 *   status). The Information Commissioner's Office (ICO) reviews the
 *   underlying personal-data handling under UK GDPR. Care Quality Commission
 *   (CQC) inspectors use DSPT submission status as a regulated-activity
 *   benchmark.
 *
 * Required of:
 *   - Every NHS organisation
 *   - Every supplier processing NHS clinical data, NHS numbers, or
 *     NHS-network-connected health data ("NHS data partner") — including
 *     AI agents that touch any NHS-tagged signal
 *
 * Key obligations encoded in this pack:
 *   1. NHS Number detection + minimum-necessary handling (NDG #1, #4)
 *   2. SNOMED-CT + ICD-10 clinical-code detection (clinical context flag)
 *   3. 8-year retention for adult clinical records (Records Management
 *      Code of Practice 2021); 25 years post-care for paediatric records;
 *      30 years for maternity records.
 *   4. Cross-NHS-trust transfer human-in-the-loop gate (NDG #4 lawful basis)
 *   5. Annual data security training assertion (NDG #3)
 *   6. Continuity / cyber-attack response posture (NDG #6, #7, #9)
 *   7. Supplier contractual flow-down (NDG #10)
 *   8. Caldicott Guardian sign-off for non-routine clinical data sharing
 *
 * Out of scope for this pack (handled by sibling packs when added):
 *   - DCB0129 / DCB0160 clinical safety case (separate pack)
 *   - MHRA SaMD UKCA marking (separate pack)
 *   - Cyber Essentials / CE+ technical control evidence (separate pack)
 *
 * Distinction from UK GDPR pack:
 *   UK GDPR governs personal-data handling at the Article-based level. NHS
 *   DSPT layers on top with NHS-specific data classes (NHS Number, clinical
 *   codes), NHS-specific retention windows, NHS-specific incident reporting
 *   (CareCERT / NHS England), and the Caldicott Guardian role. A processor
 *   handling NHS data needs BOTH packs active.
 *
 * Status: ACTIVE (Wave 1 Pack 5 of TIER 10-UK; first dependency unblocking
 *   DCB0129 / DTAC / MHRA packs per F-NEW-TIER-10-UK-WAVE1-ROADMAP).
 *
 * @connexum/ai-governance
 */
/**
 * NHS DSPT category classifiers.
 *
 * NHS_NUMBER: 10 digits with mod-11 check digit. We accept the surface form
 * (10 contiguous digits OR 3-3-4 spaced grouping) without verifying the
 * check digit at the classifier layer; downstream redactor can validate.
 *
 * SNOMED_CT: numeric concept IDs (6 to 18 digits). Surface form is highly
 * ambiguous on its own, so we require a co-located clinical context cue
 * ("snomed", "concept id", "code") to avoid false-positives on any long
 * integer.
 *
 * ICD_10: A-Z + 2 digits + optional `.X` extension (e.g. `J45.901`, `R51`).
 * Stricter pattern than the SNOMED catch-anything-numeric approach.
 *
 * CLINICAL_RECORD: free-text clinical-record indicators ("patient",
 * "diagnosis", "encounter", "consultation", "discharge summary"). Flagged
 * because NHS records are subject to the 8-year retention and Caldicott
 * sign-off rules even when no NHS Number is present.
 */
export const NHS_DSPT_CATEGORY_CLASSIFIERS = {
    NHS_NUMBER: {
        references: [
            'NHS Data Dictionary -- NHS Number specification (10-digit, mod-11)',
            'NDG Data Security Standard #1 -- personal confidential data handled securely',
            'NHS Records Management Code of Practice 2021 -- patient identifier handling',
        ],
        classifier: (input) => {
            if (/\b\d{3}\s\d{3}\s\d{4}\b/.test(input))
                return true;
            if (/\bnhs\s*(?:number|no\.?|num)[:\s]*\d{3}[\s-]?\d{3}[\s-]?\d{4}\b/i.test(input))
                return true;
            if (/\b(?:nhs|nhsno|nhsnum|patient\s+id)[:\s]+\d{10}\b/i.test(input))
                return true;
            return false;
        },
    },
    SNOMED_CT: {
        references: [
            'NHS Digital -- SNOMED CT UK Edition (mandatory clinical terminology)',
            'NHS England -- Clinical record interoperability requirements',
        ],
        classifier: (input) => {
            if (/\b(?:snomed[\s_-]?ct|snomed)\b[^.]{0,40}\b\d{6,18}\b/i.test(input))
                return true;
            if (/\b(?:concept[\s_-]?id|conceptid|sctid)[:\s]*\d{6,18}\b/i.test(input))
                return true;
            return false;
        },
    },
    ICD_10: {
        references: [
            'WHO ICD-10; NHS Digital adoption',
            'Records Management Code of Practice 2021 -- diagnosis coding',
        ],
        classifier: (input) => {
            if (/\b(?:icd[\s_-]?10|icd10)\b[^.]{0,40}\b[A-Z]\d{2}(?:\.\d{1,3})?\b/i.test(input))
                return true;
            if (/\b(?:diagnosis|dx)[:\s]+[A-Z]\d{2}\.\d{1,3}\b/i.test(input))
                return true;
            return false;
        },
    },
    CLINICAL_RECORD: {
        references: [
            'Caldicott Principles (2020 revision) -- principle 1: justify the purpose',
            'NHS Records Management Code of Practice 2021 -- clinical record retention',
            'NDG Data Security Standard #4 -- lawful basis for sharing',
        ],
        classifier: (input) => {
            if (/\b(?:patient\s+(?:record|notes|file|history|encounter|consultation|admission|discharge\s+summary))\b/i.test(input))
                return true;
            if (/\b(?:clinical\s+(?:record|notes|history|assessment|finding|impression))\b/i.test(input))
                return true;
            if (/\b(?:gp\s+(?:notes|record|summary)|primary\s+care\s+record|secondary\s+care\s+record|hospital\s+episode)\b/i.test(input))
                return true;
            if (/\b(?:caldicott|caldicott\s+guardian|smartcard|nhs\s+spine|spine\s+mini\s+services)\b/i.test(input))
                return true;
            return false;
        },
    },
    PII: {
        references: ['UK GDPR Art. 4(1) -- personal data; NHS DSPT inherits UK GDPR PII rules'],
        classifier: (input) => {
            if (/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/.test(input))
                return true;
            if (/\b[A-CEGHJ-PR-TW-Z]{2}\s?\d{2}\s?\d{2}\s?\d{2}\s?[A-D]\b/i.test(input))
                return true;
            if (/\b(?:date\s+of\s+birth|dob|d\.o\.b\.?)[:\s]+\d{1,2}[\/\-\.]\d{1,2}[\/\-\.]\d{2,4}\b/i.test(input))
                return true;
            return false;
        },
    },
    CREDENTIALS: {
        references: ['NDG Data Security Standard #2 -- access rights review'],
        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 (/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/.test(input))
                return true;
            return false;
        },
    },
};
export const NHS_DSPT_PACK = {
    categoryClassifiers: NHS_DSPT_CATEGORY_CLASSIFIERS,
    id: 'nhs-dspt',
    aliases: ['nhs-data-security-protection-toolkit', 'dspt'],
    name: 'NHS Data Security and Protection Toolkit',
    version: '1.0.0',
    description: 'NHS England DSPT compliance pack covering the NDG ten data security standards, NHS Number / SNOMED CT / ICD-10 classification, 8-year clinical record retention (paediatric 25-year / maternity 30-year), Caldicott Guardian sign-off for non-routine sharing, and the cross-NHS-trust transfer HITL gate. Required of every NHS organisation and every supplier processing NHS clinical data. Sits alongside UK GDPR for personal-data handling and is the first-dependency pack for DCB0129 / DTAC / MHRA Wave 1 packs (per F-NEW-TIER-10-UK-WAVE1-ROADMAP).',
    authority: 'NHS England (DSPT) + National Data Guardian (NDG) + ICO (UK GDPR overlay) + Care Quality Commission (CQC enforcement)',
    industries: ['healthcare', 'pharma', 'public-sector', 'digital-health', 'clinical-research'],
    requiredModules: [
        {
            name: 'data-classifier',
            required: true,
            reason: 'NHS Number, SNOMED-CT, and ICD-10 detection; clinical-record context flagging for Caldicott sign-off routing.',
            reference: 'NDG Data Security Standard #1 -- personal confidential data; NHS Records Management Code of Practice 2021',
        },
        {
            name: 'governance-runtime',
            required: true,
            reason: 'NDG Standard #4 lawful-basis enforcement on NHS data flows; minimum-necessary policy gate; Caldicott principle 1 justify-the-purpose check.',
            reference: 'Caldicott Principles (2020); NDG #4 lawful basis for sharing',
        },
        {
            name: 'approval-queue',
            required: true,
            reason: 'Cross-NHS-trust transfer HITL T2 gate; non-routine clinical data sharing requires Caldicott Guardian sign-off; AI-driven clinical decision suggestions require clinician review.',
            reference: 'Caldicott Principles -- principle 6: every use of confidential information must be lawful; NHS England guidance on cross-trust data sharing',
        },
        {
            name: 'audit-integrity',
            required: true,
            reason: 'Tamper-evident audit chain for NHS-tagged data flows; required by DSPT submission Section 9 (auditable record of access) and CQC inspection evidence.',
            reference: 'NDG #2 access rights review; DSPT submission requirements; CQC well-led KLOE evidence',
        },
        {
            name: 'attestation-manager',
            required: true,
            reason: 'DSPT submission status, annual data security training records, supplier contractual flow-down attestations, Caldicott Guardian designation. Toolkit is assertion-based: every claim must have evidence.',
            reference: 'NDG #3 annual training; NDG #10 supplier accountability; DSPT assertion model',
        },
        {
            name: 'event-bus',
            required: true,
            reason: 'CareCERT cyber incident reporting; NHS England near-miss reporting (Section 12 of DSPT); Information Commissioner notification when DSPT incident also constitutes a UK GDPR personal data breach.',
            reference: 'NDG #6 cyber attacks resisted; NDG #7 continuity plan; NHS Digital CareCERT reporting; UK GDPR Art. 33',
        },
        {
            name: 'agent-auth',
            required: true,
            reason: 'NHS smartcard / role-based access integration; access rights review per NDG #2; service-account separation for AI agents accessing NHS-tagged data.',
            reference: 'NDG #2 access rights review; NHS Identity and Access Management standard',
        },
        {
            name: 'encryption-layer',
            required: true,
            reason: 'NHS data encrypted at rest and in transit; DSPT Section 7 evidence requirements; UK GDPR Art. 32(1)(a) overlay.',
            reference: 'DSPT Section 7 -- secure systems; NDG #1 secure handling; UK GDPR Art. 32(1)(a)',
        },
        {
            name: 'session-persistence',
            required: true,
            reason: 'Records Management Code of Practice 2021 retention enforcement: 8-year adult clinical, 25-year paediatric (until 25th birthday), 30-year maternity. Storage limitation gate.',
            reference: 'NHS Records Management Code of Practice 2021; UK GDPR Art. 5(1)(e)',
        },
        {
            name: 'supply-chain',
            required: true,
            reason: 'Supplier contractual flow-down per NDG #10; sub-processor DSPT submission evidence chain; data processor contracts include DSPT obligations.',
            reference: 'NDG #10 IT suppliers held accountable; UK GDPR Art. 28; DSPT Section 8 supplier evidence',
        },
        {
            name: 'transparency-injector',
            required: true,
            reason: 'Patient-facing AI use disclosure; National Data Opt-Out compliance check; Caldicott principle 7 (duty to share) balanced with patient choice.',
            reference: 'Caldicott Principles -- principle 7 duty to share; National Data Opt-Out policy 2018',
        },
    ],
    moduleConfig: {
        'data-classifier': {
            enabledCategories: ['NHS_NUMBER', 'SNOMED_CT', 'ICD_10', 'CLINICAL_RECORD', 'PII', 'CREDENTIALS'],
            nhsNumberAction: 'BLOCK',
            snomedCtAction: 'WARN',
            icd10Action: 'WARN',
            clinicalRecordAction: 'WARN',
            caldicottRoutingRequired: true,
        },
        'governance-runtime': {
            lawfulBasisEnforced: true,
            minimumNecessaryRequired: true,
            caldicottPrinciple1JustifyPurpose: true,
            crossTrustTransferGated: true,
        },
        'approval-queue': {
            crossNhsTrustHumanReviewRequired: true,
            caldicottGuardianSignOffRequired: true,
            clinicalDecisionAiHumanReviewRequired: true,
            reviewTier: 'T2',
        },
        'audit-integrity': {
            tamperEvidentRequired: true,
            dsptSection9EvidenceTrackingRequired: true,
        },
        'attestation-manager': {
            dsptSubmissionTracked: true,
            annualDataSecurityTrainingTracked: true,
            supplierFlowDownTracked: true,
            caldicottGuardianDesignationTracked: true,
        },
        'event-bus': {
            careCertReportingRequired: true,
            icoBreachOverlayRequired: true,
            nhsEnglandNearMissReportingHours: 72,
        },
        'session-persistence': {
            retentionDaysAdultClinical: 2920, // 8 years
            retentionDaysPaediatric: 9125, // 25 years (placeholder; real rule is until 25th birthday)
            retentionDaysMaternity: 10950, // 30 years
            storageLimitationEnforced: true,
        },
        'supply-chain': {
            processorContractRequired: true,
            ndg10FlowDownRequired: true,
            subProcessorDsptEvidenceRequired: true,
        },
        'encryption-layer': {
            algorithm: 'aes-256-gcm',
            encryptionRequiredForNhsData: true,
        },
        'agent-auth': {
            nhsSmartcardSupported: true,
            accessRightsReviewIntervalDays: 90,
        },
        'transparency-injector': {
            patientFacingAiDisclosureRequired: true,
            nationalDataOptOutHonoured: true,
        },
    },
    providerPolicy: {
        blockedProviders: ['deepseek', 'baidu', 'alibaba'],
        requiredCapabilities: ['DATA-RESIDENCY-UK', 'PROCESSOR-CONTRACT', 'NHS-DSPT-SUBSCRIBED'],
        blockReasons: {
            deepseek: 'PRC National Intelligence Law incompatible with UK GDPR Art. 46 transfer safeguards and DSPT cross-border restriction. NHS data must reside in UK or adequate jurisdiction.',
            baidu: 'PRC jurisdiction. No UK adequacy. NHS data residency requirement violated.',
            alibaba: 'PRC jurisdiction. No UK adequacy. NHS data residency requirement violated.',
        },
    },
    dataPolicy: {
        scanCategories: ['NHS_NUMBER', 'SNOMED_CT', 'ICD_10', 'CLINICAL_RECORD', 'PII', 'CREDENTIALS'],
        categoryActions: {
            NHS_NUMBER: 'BLOCK',
            SNOMED_CT: 'WARN',
            ICD_10: 'WARN',
            CLINICAL_RECORD: 'WARN',
            PII: 'WARN',
            CREDENTIALS: 'BLOCK',
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256-GCM',
        minimumClassification: 'RESTRICTED',
    },
    retentionPolicy: {
        // NHS Records Management Code of Practice 2021:
        //   Adult clinical record: 8 years from last contact
        //   Paediatric: until 25th birthday OR 26th if patient died (here we use
        //     25 years as a generous upper bound; per-record date-of-birth logic
        //     belongs in session-persistence, not the policy default)
        //   Maternity: 25 years from birth of child (we use 30 to harmonise
        //     with the longest-form maternal-mortality investigation window)
        auditLogRetentionDays: 2920, // 8 years
        sessionRetentionDays: 2920,
        incidentRetentionDays: 2920,
        reference: 'NHS Records Management Code of Practice 2021 (TNA / NHSX); 8-year adult clinical default; paediatric until 25th birthday; maternity 25-30 years; UK GDPR Art. 5(1)(e) storage limitation',
        forceDelete: false,
        requiresLegalHoldSupport: true,
        sovereignty: ['gb'],
    },
    incidentPolicy: {
        // CareCERT (NHS Digital) and NHS England Section 12 near-miss reporting
        // are the NHS-specific channels. UK GDPR Art. 33 72-hour ICO notification
        // applies in parallel when the incident is also a personal-data breach.
        notificationDeadlineHours: 72,
        reference: 'NHS Digital CareCERT incident reporting; NHS England Section 12 near-miss; UK GDPR Art. 33 (72-hour ICO notification); NDG #6/#7 cyber-attack response',
        requiredRecipients: [
            'caldicott-guardian',
            'senior-information-risk-owner',
            'nhs-england-carecert',
            'data-protection-officer',
            'ico',
        ],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: 'nhs-dspt-data-classifier',
            description: 'Data classifier active for NHS Number / SNOMED-CT / ICD-10 / clinical-record categories with NHS Number set to BLOCK and Caldicott routing enabled.',
            reference: 'NDG #1 secure handling; Caldicott principle 1 justify the purpose',
            check: 'data_classifier_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-dspt-cross-trust-hitl',
            description: 'Cross-NHS-trust data transfer subject to T2 human-in-the-loop review; Caldicott Guardian sign-off captured.',
            reference: 'Caldicott Principles -- principle 6 lawful sharing; NDG #4 lawful basis',
            check: 'approval_queue_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-dspt-encryption',
            description: 'NHS data encrypted at rest and in transit per DSPT Section 7 and UK GDPR Art. 32(1)(a).',
            reference: 'DSPT Section 7 secure systems; NDG #1 secure handling; UK GDPR Art. 32(1)(a)',
            check: 'encryption_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-dspt-audit-trail',
            description: 'Tamper-evident audit chain active for NHS-tagged data flows; supports DSPT Section 9 evidence requirement.',
            reference: 'NDG #2 access rights review; DSPT Section 9; CQC well-led KLOE',
            check: 'audit_trail_exists',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-dspt-incident-72h',
            description: 'Incident notification path active to CareCERT + Caldicott Guardian + SIRO + ICO within 72 hours when DSPT incident is also a UK GDPR breach.',
            reference: 'CareCERT reporting; NDG #6 cyber attacks resisted; NDG #7 continuity; UK GDPR Art. 33',
            check: 'monitoring_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-dspt-retention-8yr',
            description: '8-year adult clinical retention enforced; paediatric / maternity overrides supported via per-record date-of-birth metadata.',
            reference: 'NHS Records Management Code of Practice 2021',
            check: 'retention_policy_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-dspt-supplier-flow-down',
            description: 'NDG #10 supplier contractual flow-down recorded; sub-processor DSPT submission evidence captured.',
            reference: 'NDG #10 IT suppliers accountability; UK GDPR Art. 28',
            check: 'subservice_registry_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-dspt-annual-training',
            description: 'Annual data security training attestation recorded for all staff with NHS data access.',
            reference: 'NDG #3 annual training; DSPT submission Section 3',
            check: 'attestation_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-dspt-access-rights-review',
            description: 'Access rights reviewed at least every 90 days; smartcard / role binding kept current.',
            reference: 'NDG #2 access rights review',
            check: 'rbac_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-dspt-national-opt-out',
            description: 'National Data Opt-Out honoured for non-direct-care purposes (research, planning).',
            reference: 'National Data Opt-Out policy 2018; Caldicott principle 7',
            check: 'transparency_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-dspt-caldicott-guardian-designated',
            description: 'Caldicott Guardian designation recorded and current; sign-off path wired into approval-queue.',
            reference: 'Caldicott Principles 2020; NHS England Caldicott Guardian Manual',
            check: 'attestation_active',
            failSeverity: 'MEDIUM',
        },
    ],
};
//# sourceMappingURL=nhs-dspt.js.map