/**
 * 340B Drug Pricing Program + DSCSA Compliance Pack
 *
 * 340B Drug Pricing Program: 42 U.S.C. §256b — HRSA OPA audit requirements
 * Drug Supply Chain Security Act: 21 U.S.C. §360eee-1 — FDA DSCSA
 *
 * Enforces 7 of 8 rules from rules.md:
 *   BLOCK: 340B-001 (eligibility three-prong), 340B-002 (duplicate discount),
 *          340B-004 (DSCSA TI completeness), 340B-005 (serialization verify),
 *          340B-006 (suspect product investigation)
 *   WARN:  340B-003 (contract pharmacy audit trail), 340B-007 (retention classification)
 *   SKIP:  340B-008 — human-attestation (trading partner licensure), not wired here
 *
 * @connexum/ai-governance | Kai (CXNI-005) | 2026-05-24
 */
export const B340_DSCSA_CATEGORY_CLASSIFIERS = {
    /**
     * 340B-001 — BLOCK
     * 340B patient eligibility determinations must link to a qualifying encounter.
     * Three-prong test: qualifying encounter + covered entity prescriber + covered entity scope.
     * HRSA 340B program requirements / OPA audit guide
     *
     * enforcement_pattern: semantic:340b-eligibility-three-prong
     */
    B340_ELIGIBILITY_INCOMPLETE: {
        references: ['42 U.S.C. §256b — 340B three-prong eligibility test; HRSA OPA audit guide'],
        classifier: (input) => {
            // Must be a 340B eligibility determination (matches both JSON snake_case and natural language)
            const is340bEligibility = /(340[Bb][_\s-]?(eligibility|eligible|patient|determination)|340[Bb][-_\s]eligible|covered[_\s]entity[_\s]patient|determination.*340[Bb]|340[Bb].*determination)/i.test(input);
            if (!is340bEligibility)
                return false;
            // Check for all three prongs of the eligibility test (matches JSON field names and natural language)
            const hasQualifyingEncounter = /(qualifying[_\s]encounter|encounter[_\s]id|encounter\s+number|encounter\s+linked|visit\s+at\s+(covered\s+entity|CE))/i.test(input);
            const hasCoveredEntityPrescriber = /(covered\s+entity\s+prescriber|CE\s+prescriber|prescriber[_\s]npi|encounter[_\s]provider[_\s]npi|provider[_\s]employment[_\s]status|prescriber\s+(employed|contracted)\s+by)/i.test(input);
            const hasCoveredEntityScope = /(covered[_\s]entity[_\s]scope|CE\s+scope|scope\s+of\s+care|within\s+(the\s+)?scope|covered[_\s]entity[_\s]scope[_\s]confirmed)/i.test(input);
            return !hasQualifyingEncounter || !hasCoveredEntityPrescriber || !hasCoveredEntityScope;
        },
    },
    /**
     * 340B-002 — BLOCK
     * Duplicate discount prevention: 340B drug claims must not be routed to
     * Medicaid rebate program simultaneously.
     * 42 U.S.C. §256b(a)(5)(A)
     *
     * enforcement_pattern: semantic:duplicate-discount-detection
     */
    DUPLICATE_DISCOUNT_DETECTED: {
        references: ['42 U.S.C. §256b(a)(5)(A) — Prohibition on duplicate discounts'],
        classifier: (input) => {
            // Must be a pharmacy/drug claim or acquisition record (JSON or natural language)
            const isPharmacyClaim = /(pharmacy\s+claim|drug\s+claim|claim\s+line|prescription\s+claim|drug\s+acquisition|acquisition[_\s]type|claim[_\s]id|drug[_\s]ndc|medicaid[_\s]id)/i.test(input);
            if (!isPharmacyClaim)
                return false;
            // Flag if both 340B acquisition AND Medicaid rebate indicators are present on same claim
            const has340bIndicator = /(340[Bb]\s+(acquisition|acquired|pricing|price|indicator)|340[Bb][-_](discounted|indicator|eligible)|acquisition[_\s]type["']?\s*[:=]\s*["']?340[Bb]|["']340[Bb][_-](discounted|eligible|pricing)["'])/i.test(input);
            const hasMedicaidRebate = /(medicaid\s+rebate[^_\s]|rebate\s+route[d]?|state\s+rebate|medicaid\s+drug\s+rebate|MDRP|rebate[_\s]eligible["']?\s*:\s*(true|1)|medicaid[_\s]rebate[_\s]eligible["']?\s*:\s*(true|1))/i.test(input);
            return has340bIndicator && hasMedicaidRebate;
        },
    },
    /**
     * 340B-003 — WARN
     * Contract pharmacy claims must maintain a complete audit trail.
     * Required linkages: encounter + prescriber + dispense record + replenishment order.
     * HRSA contract pharmacy guidance
     *
     * enforcement_pattern: semantic:contract-pharmacy-audit-trail
     */
    CONTRACT_PHARMACY_AUDIT_TRAIL_INCOMPLETE: {
        references: ['HRSA 340B contract pharmacy guidance — four-element audit trail'],
        classifier: (input) => {
            // Must be a contract pharmacy claim
            const isContractPharmacy = /\b(contract\s+pharmacy|CP\s+claim|contract\s+pharmacy\s+(claim|dispense|record))\b/i.test(input);
            if (!isContractPharmacy)
                return false;
            const hasEncounterLink = /(encounter[_\s]link|encounter[_\s]id|patient\s+encounter\s+(linked|reference|id))/i.test(input);
            const hasPresciberLink = /(prescriber[_\s]link|prescriber[_\s]npi|prescriber\s+reference)/i.test(input);
            const hasDispenseRecord = /(dispense[_\s]record|dispense[_\s]id|pharmacy\s+dispense|dispense\s+reference)/i.test(input);
            const hasReplenishment = /(replenishment[_\s]order|replenishment[_\s]id|340[Bb]\s+replenishment|replenishment\s+reference)/i.test(input);
            return !hasEncounterLink || !hasPresciberLink || !hasDispenseRecord || !hasReplenishment;
        },
    },
    /**
     * 340B-004 — BLOCK
     * DSCSA Transaction Information (TI) must be complete for each pharmaceutical unit.
     * Required fields: proprietary name, NDC, lot number, transaction date, ship date,
     * trading partner name and address.
     * 21 U.S.C. §360eee-1(c)(1)(A)
     *
     * enforcement_pattern: regex + field-completeness check
     */
    DSCSA_TI_INCOMPLETE: {
        references: ['21 U.S.C. §360eee-1(c)(1)(A) — DSCSA Transaction Information required fields'],
        classifier: (input) => {
            // Must be a DSCSA receiving record or TI document (JSON or natural language)
            const isDscsaRecord = /(DSCSA|transaction[_\s]information|TI[_\s]document|drug[_\s]receiving|pharmaceutical[_\s]receipt|product\s+receiving|receipt[_\s]id|ti[_\s]document[_\s]present)/i.test(input);
            if (!isDscsaRecord)
                return false;
            // If TI document is explicitly marked as present, do not flag
            const tiDocumentPresent = /(ti[_\s]document[_\s]present['":\s]+true|ti[_\s](document|present)\s*[:=]\s*(true|yes|1))/i.test(input);
            if (tiDocumentPresent)
                return false;
            // If TI document explicitly absent, flag immediately
            const tiDocumentAbsent = /(ti[_\s]document[_\s]present['":\s]+false|ti[_\s](document|present)\s*[:=]\s*(false|no|0))/i.test(input);
            if (tiDocumentAbsent)
                return true;
            // Required DSCSA TI fields (check for completeness when presence flag not explicit)
            const hasNDC = /(["']?ndc["']?\s*[:=]\s*["']?\d{5}-\d{4}-\d{2}|NDC[:\s]+\d{10,11}|national\s+drug\s+code)/i.test(input);
            const hasLotNumber = /(lot[_\s]number|lot\s+#|["']lot_number["']\s*[:=]\s*["'][A-Z0-9\-]{3,20}["']|lot[:\s]+[A-Z0-9\-]{3,20})\b/i.test(input);
            const hasTransactionDate = /(transaction[_\s]date|date[_\s]of[_\s]transaction)[:\s]+\d{4}[-/]\d{2}[-/]\d{2}/i.test(input);
            const hasTradingPartner = /(trading[_\s]partner[_\s](name|address)|distributor[_\s]name|wholesaler[_\s]name|supplier[_\s]name|sender[_\s]name)/i.test(input);
            // Flag if any required field is missing
            return !hasNDC || !hasLotNumber || !hasTransactionDate || !hasTradingPartner;
        },
    },
    /**
     * 340B-005 — BLOCK
     * DSCSA product identifier verification: each sellable unit must have
     * GTIN, serial number, lot number, and expiration date verified.
     * 21 U.S.C. §360eee-1(a)(20)
     *
     * enforcement_pattern: semantic:dscsa-serialization-verify
     */
    DSCSA_SERIALIZATION_NOT_VERIFIED: {
        references: ['21 U.S.C. §360eee-1(a)(20) — DSCSA product identifier serialization requirements'],
        classifier: (input) => {
            // Must be a pharmaceutical receiving workflow output
            const isReceiving = /\b(product\s+receiving|pharmaceutical\s+receiving|inventory\s+receipt|drug\s+receipt|receiving\s+record|DSCSA)\b/i.test(input);
            if (!isReceiving)
                return false;
            // Flag if serialization verification result is absent
            const hasSerializationVerification = /(serialization[_\s](verified?|verification|check|result)|barcode[_\s](verified?|scanned?|validation)|GTIN[_\s](verified?|confirmed?)|verification[_\s]result[:\s]+(pass|verified?|success|complete))/i.test(input);
            // Also flag if explicit verification failure is present without suspect product workflow
            const hasVerificationFailure = /(verification[_\s](failed?|failure|error)|barcode[_\s](mismatch|error|failed?)|serialization[_\s](error|mismatch))/i.test(input);
            if (hasVerificationFailure) {
                // Failure without suspect product workflow is handled by 340B-006
                return false;
            }
            return !hasSerializationVerification;
        },
    },
    /**
     * 340B-006 — BLOCK
     * Suspect product investigation workflow must be initiated when a
     * verification failure is detected.
     * 21 U.S.C. §360eee-1(h)
     *
     * enforcement_pattern: semantic:suspect-product-flag
     */
    SUSPECT_PRODUCT_WORKFLOW_NOT_INITIATED: {
        references: ['21 U.S.C. §360eee-1(h) — DSCSA suspect product investigation requirements'],
        classifier: (input) => {
            // Must have a verification failure indicator (JSON fields or Python code or natural language)
            const hasVerificationFailure = /(verification[_\s](failed?|failure|negative)|barcode[_\s](mismatch|error|failed?)|serialization[_\s](error|mismatch|failed?)|suspect[_\s]product|illegitimate[_\s]product|database[_\s]negative|status\s*==\s*["']NEGATIVE["']|scan_result\.status.*NEGATIVE|["']NEGATIVE["'])/i.test(input);
            if (!hasVerificationFailure)
                return false;
            // Check that suspect product workflow was initiated
            const hasWorkflowInitiated = /(suspect[_\s]product[_\s]workflow[_\s]initiated\s*[:=]\s*(true|yes|1)|quarantine[_\s](initiated|placed|flagged)|suspect[_\s]product\s+(quarantine|investigation|workflow)\s+(initiated|started|begun))/i.test(input);
            return !hasWorkflowInitiated;
        },
    },
    /**
     * 340B-007 — WARN
     * 340B transaction records must include a retention classification tag (3-year minimum).
     * HRSA 340B program audit requirements
     *
     * enforcement_pattern: semantic:retention-classification-missing
     */
    B340_RETENTION_CLASSIFICATION_MISSING: {
        references: ['HRSA 340B program audit requirements — 3-year minimum record retention'],
        classifier: (input) => {
            // Must be a 340B transaction record
            const is340bRecord = /\b(340[Bb]\s+(transaction|record|eligibility|replenishment|claim)|340[Bb][-_]transaction)\b/i.test(input);
            if (!is340bRecord)
                return false;
            // Check for retention classification tag
            const hasRetentionTag = /(retention[_\s](class|classification|tag|category)[:\s]*["']?340[Bb]|retention[_\s]class[:\s]*["']?340[Bb]-3yr["']?|retain\s+for\s+(3|three)\s+year)/i.test(input);
            return !hasRetentionTag;
        },
    },
};
export const B340_DSCSA_PACK = {
    categoryClassifiers: B340_DSCSA_CATEGORY_CLASSIFIERS,
    id: '340b-dscsa',
    name: '340B Drug Pricing Program + DSCSA',
    version: '1.0.0',
    contentHash: '56c74c2cd1ecf8e03b89a9f5d4209c0a1349febb4b156bcb0a5e64bd5bcb86a9',
    description: '340B Drug Pricing Program audit compliance (HRSA OPA) and Drug Supply Chain Security Act (DSCSA) traceability. Covers 340B patient eligibility three-prong test, duplicate discount prevention, contract pharmacy audit trail, DSCSA serialization verification, and suspect product investigation.',
    authority: 'HRSA Office of Pharmacy Affairs (340B); FDA (DSCSA)',
    industries: ['healthcare', 'pharmacy', 'hospital', 'covered-entity', 'drug-supply-chain'],
    requiredModules: [
        {
            name: 'audit-integrity',
            required: true,
            reason: '340B audit trail completeness for HRSA OPA audits',
            reference: 'HRSA 340B program audit requirements',
        },
        {
            name: 'governance-runtime',
            required: true,
            reason: 'Block 340B eligibility determinations missing three-prong test',
            reference: '42 U.S.C. §256b',
        },
        {
            name: 'data-classifier',
            required: true,
            reason: 'DSCSA serialization verification and duplicate discount detection',
            reference: '21 U.S.C. §360eee-1',
        },
    ],
    moduleConfig: {
        'audit-integrity': {
            retentionDays: 1095, // 3 years per HRSA 340B audit requirements
        },
        'governance-runtime': {
            denyByDefaultRequired: true,
        },
    },
    providerPolicy: {
        blockedProviders: [],
        requiredCapabilities: [],
        blockReasons: {},
    },
    dataPolicy: {
        scanCategories: [
            'B340_ELIGIBILITY_INCOMPLETE',
            'DUPLICATE_DISCOUNT_DETECTED',
            'CONTRACT_PHARMACY_AUDIT_TRAIL_INCOMPLETE',
            'DSCSA_TI_INCOMPLETE',
            'DSCSA_SERIALIZATION_NOT_VERIFIED',
            'SUSPECT_PRODUCT_WORKFLOW_NOT_INITIATED',
            'B340_RETENTION_CLASSIFICATION_MISSING',
        ],
        categoryActions: {
            B340_ELIGIBILITY_INCOMPLETE: 'BLOCK',
            DUPLICATE_DISCOUNT_DETECTED: 'BLOCK',
            CONTRACT_PHARMACY_AUDIT_TRAIL_INCOMPLETE: 'WARN',
            DSCSA_TI_INCOMPLETE: 'BLOCK',
            DSCSA_SERIALIZATION_NOT_VERIFIED: 'BLOCK',
            SUSPECT_PRODUCT_WORKFLOW_NOT_INITIATED: 'BLOCK',
            B340_RETENTION_CLASSIFICATION_MISSING: 'WARN',
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256-GCM',
        minimumClassification: 'RESTRICTED',
    },
    retentionPolicy: {
        auditLogRetentionDays: 1095,
        sessionRetentionDays: 1095,
        incidentRetentionDays: 1095,
        reference: 'HRSA 340B program audit requirements — 3-year retention',
        forceDelete: false,
        requiresLegalHoldSupport: true,
        sovereignty: ['us'],
    },
    incidentPolicy: {
        notificationDeadlineHours: 72,
        reference: '21 U.S.C. §360eee-1(h) — FDA illegitimate product reporting',
        requiredRecipients: ['pharmacy-director', 'compliance-officer', 'fda'],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: '340b-eligibility-check',
            description: '340B patient eligibility three-prong test classifier active',
            reference: '42 U.S.C. §256b',
            check: 'data_classifier_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'dscsa-serialization-check',
            description: 'DSCSA product serialization verification classifier active',
            reference: '21 U.S.C. §360eee-1',
            check: 'data_classifier_active',
            failSeverity: 'CRITICAL',
        },
    ],
    requiresRetrievalAuditLogging: true,
    maxAutonomyLevelWithoutAttestation: 2,
    recommendedHookProfile: 'strict',
};
//# sourceMappingURL=340b-dscsa.js.map