// crispr.sy -- CRISPR-Cas gene editing systems as native Scyla.
//
// Sources:
//   Doudna JA, Charpentier E. Science 346:1258096, 2014.
//   Anzalone AV et al. Nature 576:149-157, 2019.
//   Doench JG et al. Nat Biotechnol 34:184-191, 2016.
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536

// ═══════════════════════════════════════════════════════
// STRUCTS
// ═══════════════════════════════════════════════════════

struct CasVariant {
    name: String,
    organism: String,
    pam_sequence: String,
    cut_type: String,
    target_type: String,
    size_aa: Int,
    delivery_compatible: String,
    clinical_stage: String,
    citation: String,
}

struct GuideRNARule {
    rule_name: String,
    description: String,
    optimal_value: String,
    citation: String,
}

struct DeliveryMethod {
    name: String,
    mechanism: String,
    packaging_limit: String,
    advantages: String,
    limitations: String,
    clinical_use: String,
    citation: String,
}

struct ClinicalTrial {
    name: String,
    trade_name: String,
    target_gene: String,
    cas_system: String,
    indication: String,
    sponsor: String,
    approval_status: String,
    mechanism: String,
    citation: String,
}

struct RepairPathway {
    pathway: String,
    full_name: String,
    mechanism: String,
    fidelity: String,
    efficiency: String,
    cell_cycle_phase: String,
    key_proteins: String,
    applications: String,
    citation: String,
}

struct OffTargetResult {
    score: Float,
    interpretation: String,
}

struct OnTargetFeature {
    feature_name: String,
    position: String,
    preferred: String,
    effect: String,
    citation: String,
}

// ═══════════════════════════════════════════════════════
// CONSTRUCTOR HELPERS
// ═══════════════════════════════════════════════════════

fn casvar(n: String, o: String, p: String, ct: String, tt: String, sa: Int, dc: String, cs: String, ci: String) -> CasVariant {
    return CasVariant { name: n, organism: o, pam_sequence: p, cut_type: ct, target_type: tt, size_aa: sa, delivery_compatible: dc, clinical_stage: cs, citation: ci }
}

fn grule(rn: String, d: String, ov: String, ci: String) -> GuideRNARule {
    return GuideRNARule { rule_name: rn, description: d, optimal_value: ov, citation: ci }
}

fn dmethod(n: String, me: String, pl: String, ad: String, li: String, cu: String, ci: String) -> DeliveryMethod {
    return DeliveryMethod { name: n, mechanism: me, packaging_limit: pl, advantages: ad, limitations: li, clinical_use: cu, citation: ci }
}

fn ctrial(n: String, tn: String, tg: String, cs: String, ind: String, sp: String, ap: String, me: String, ci: String) -> ClinicalTrial {
    return ClinicalTrial { name: n, trade_name: tn, target_gene: tg, cas_system: cs, indication: ind, sponsor: sp, approval_status: ap, mechanism: me, citation: ci }
}

fn rpathway(p: String, fn_name: String, me: String, fi: String, ef: String, cc: String, kp: String, ap: String, ci: String) -> RepairPathway {
    return RepairPathway { pathway: p, full_name: fn_name, mechanism: me, fidelity: fi, efficiency: ef, cell_cycle_phase: cc, key_proteins: kp, applications: ap, citation: ci }
}

fn otresult(s: Float, i: String) -> OffTargetResult {
    return OffTargetResult { score: s, interpretation: i }
}

fn otfeature(fn_val: String, po: String, pr: String, ef: String, ci: String) -> OnTargetFeature {
    return OnTargetFeature { feature_name: fn_val, position: po, preferred: pr, effect: ef, citation: ci }
}

// ═══════════════════════════════════════════════════════
// CAS VARIANTS -- the molecular scissors
// ═══════════════════════════════════════════════════════
//
// Each variant has evolved (or been engineered) for different
// PAM requirements, cut geometries, and target substrates.
// The diversity of Cas effectors is what makes CRISPR a
// platform technology rather than a single tool.

fn cas_variant(name: String) -> CasVariant {
    // SpCas9: the workhorse, first characterized for genome editing
    if name == "SpCas9" { return casvar("SpCas9", "Streptococcus pyogenes", "NGG", "Blunt dsDNA break 3 bp upstream of PAM. HNH domain cuts target strand, RuvC cuts non-target strand.", "DNA", 1368, "AAV (too large, requires split-intein), LNP, electroporation, RNP", "FDA approved (Casgevy, Dec 2023). Most clinically advanced.", "Jinek M et al. Science 337:816-821, 2012. Doudna & Charpentier, Science 346:1258096, 2014.") }

    // Cas9 nickase D10A: RuvC inactivated, cuts only target strand
    if name == "Cas9_D10A" { return casvar("Cas9 nickase (D10A)", "S. pyogenes (engineered)", "NGG", "Single-strand nick on target strand only. RuvC domain inactivated by D10A mutation. Used in paired nickase strategy: two guides flanking target, each nicking one strand. Reduces off-targets by requiring two proximal binding events.", "DNA", 1368, "LNP, electroporation, RNP", "Used in base editors (CBE). Clinical trials ongoing.", "Ran FA et al. Cell 154:1380-1389, 2013.") }

    // Cas9 nickase H840A: HNH inactivated, cuts only non-target strand
    if name == "Cas9_H840A" { return casvar("Cas9 nickase (H840A)", "S. pyogenes (engineered)", "NGG", "Single-strand nick on non-target strand only. HNH domain inactivated by H840A mutation. Used in prime editing (PE) fused to reverse transcriptase.", "DNA", 1368, "LNP, electroporation, RNP", "Used in prime editors. Clinical development.", "Anzalone AV et al. Nature 576:149-157, 2019.") }

    // SaCas9: smaller, fits AAV
    if name == "SaCas9" { return casvar("SaCas9", "Staphylococcus aureus", "NNGRRT", "Blunt dsDNA break. Functionally similar to SpCas9 but 25% smaller. Fits in single AAV vector with guide RNA and promoter.", "DNA", 1053, "AAV (fits single vector), LNP, electroporation, RNP", "In vivo gene editing via AAV. Preclinical and Phase I.", "Ran FA et al. Nature 520:186-191, 2015.") }

    // Cas12a (Cpf1): staggered cuts, self-processing crRNA
    if name == "Cas12a" { return casvar("Cas12a (Cpf1)", "Acidaminococcus sp. (AsCas12a), Lachnospiraceae bacterium (LbCas12a)", "TTTV (V = A, C, or G)", "Staggered dsDNA cut producing 4-5 nt 5-prime overhangs. Single RuvC-like domain cuts both strands sequentially. Cut site is 18-23 nt distal to PAM. Processes own crRNA array (no tracrRNA needed). T-rich PAM enables targeting AT-rich regions inaccessible to SpCas9.", "DNA", 1307, "LNP, electroporation, RNP, AAV (tight but feasible)", "DETECTR diagnostics (Mammoth Biosciences). Therapeutic programs in development.", "Zetsche B et al. Cell 163:759-771, 2015.") }

    // Cas12b (C2c1)
    if name == "Cas12b" { return casvar("Cas12b (C2c1)", "Alicyclobacillus acidiphilus (AaCas12b)", "TTN", "dsDNA cleavage with staggered ends. Requires both crRNA and tracrRNA unlike Cas12a. Thermostable (active at 48C). Smaller than Cas12a.", "DNA", 1108, "LNP, electroporation, RNP", "Early preclinical. Potential for thermophilic applications.", "Teng F et al. Cell Discov 4:63, 2018.") }

    // Cas13a (C2c2): RNA targeting, collateral cleavage
    if name == "Cas13a" { return casvar("Cas13a (C2c2)", "Leptotrichia shahii (LshCas13a)", "PFS: non-G 3-prime of target (protospacer flanking site)", "Cleaves ssRNA at target site. Upon target recognition, activates collateral cleavage: indiscriminate degradation of nearby ssRNA. Two HEPN domains mediate RNA cleavage.", "RNA", 1389, "LNP, electroporation (ex vivo RNA knockdown)", "SHERLOCK diagnostics platform (Specific High-sensitivity Enzymatic Reporter unLOCKing). Sherlock Biosciences. EUA for SARS-CoV-2 detection.", "Abudayyeh OO et al. Science 353:aaf5573, 2016. Gootenberg JS et al. Science 356:438-442, 2017 (SHERLOCK).") }

    // Cas13d (CasRx): RNA knockdown without collateral
    if name == "Cas13d" { return casvar("Cas13d (CasRx)", "Ruminococcus flavefaciens (RfxCas13d)", "No PFS requirement", "Cleaves target ssRNA with high specificity. Minimal collateral cleavage compared to Cas13a. Smallest known Cas13 effector. Two HEPN domains. Highly efficient RNA knockdown (median 96% knockdown).", "RNA", 967, "AAV (fits single vector due to small size), LNP, electroporation", "Preclinical RNA knockdown therapeutics. Potential replacement for RNAi. Smaller than all other Cas13 family members.", "Konermann S et al. Cell 173:665-676, 2018.") }

    // CBE: cytosine base editor (C-to-T without DSB)
    if name == "CBE" { return casvar("Cytosine Base Editor (CBE, BE4max)", "Engineered: rAPOBEC1 + Cas9 D10A nickase + UGI", "NGG (SpCas9-based)", "No DSB. Cytidine deaminase (rAPOBEC1) converts C to U in a 4-8 nt editing window (positions 4-8 counting from PAM-distal end of protospacer). Cell reads U as T after replication. Nickase cuts non-edited strand to bias repair toward edited strand. UGI (uracil glycosylase inhibitor) prevents base excision repair from reverting edit. Net result: C-to-T (G-to-A on opposite strand).", "DNA", 1853, "LNP, electroporation, RNP (large construct)", "Beam Therapeutics: BEAM-101 for sickle cell disease (clinical trial). Multiple preclinical programs.", "Komor AC et al. Nature 533:420-424, 2016. Koblan LW et al. Nat Biotechnol 36:843-846, 2018 (BE4max).") }

    // ABE: adenine base editor (A-to-G without DSB)
    if name == "ABE" { return casvar("Adenine Base Editor (ABE, ABE8e)", "Engineered: evolved TadA* + Cas9 D10A nickase", "NGG (SpCas9-based)", "No DSB. Evolved adenosine deaminase (TadA*) converts A to inosine (I) in editing window (positions 4-8). Cell reads I as G after replication. Nickase cuts non-edited strand. Net result: A-to-G (T-to-C on opposite strand). Complementary to CBE: together they enable 4 of 12 possible point mutations without DSB.", "DNA", 1685, "LNP, electroporation, RNP", "Beam Therapeutics: BEAM-101 for SCD uses ABE to mimic HPFH. Verve Therapeutics: VERVE-101 for heterozygous familial hypercholesterolemia (PCSK9 base editing in liver via LNP, in vivo). First in vivo base editing in humans (2022).", "Gaudelli NM et al. Nature 551:464-471, 2017. Richter MF et al. Nat Biotechnol 38:883-891, 2020 (ABE8e).") }

    // Prime editing: all twelve point mutations plus small indels
    if name == "PE" { return casvar("Prime Editor (PE, PE2/PE3/PEmax)", "Engineered: Cas9 H840A nickase fused to M-MLV reverse transcriptase", "NGG (SpCas9-based)", "No DSB. Uses pegRNA (prime editing guide RNA) containing: (a) spacer for target binding, (b) primer binding site (PBS) that anneals to nicked strand, (c) RT template encoding desired edit. H840A nicks target strand, PBS anneals, RT synthesizes new DNA from template. Enables all twelve point mutations, small insertions (up to 44 bp demonstrated), small deletions (up to 80 bp), and combinations thereof. PE3 adds second nick on non-edited strand to improve efficiency.", "DNA", 2038, "LNP (large cargo), electroporation, dual-AAV (split)", "Prime Medicine: clinical trials initiated. Preclinical programs for SCD, liver diseases. Most versatile editing tool but lowest efficiency of precision editors.", "Anzalone AV et al. Nature 576:149-157, 2019.") }

    return casvar("", "", "", "", "", 0, "", "", "")
}

fn cas_variant_count() -> Int {
    return 12
}

// ═══════════════════════════════════════════════════════
// GUIDE RNA DESIGN RULES
// ═══════════════════════════════════════════════════════
//
// A perfectly designed guide RNA is the difference between
// a clean edit and a mutagenic disaster. These rules derive
// from large-scale screening studies (Doench 2016) and
// mechanistic understanding of Cas9-DNA interaction.

fn grna_design_rule(rule: String) -> GuideRNARule {
    // GC content: thermodynamic stability of guide-target hybrid
    if rule == "gc_content" { return grule("GC content 40-60%", "GC content of the 20 nt spacer should be 40-60%. Below 40%: weak guide-target binding, low activity. Above 60%: stable off-target binding, increased mismatch tolerance. 50-60% is ideal for SpCas9.", "40-60% (optimal ~55%)", "Wang T et al. Science 343:80-84, 2014. Doench JG et al. Nat Biotechnol 34:184-191, 2016.") }

    // Pol III terminator avoidance
    if rule == "avoid_tttt" { return grule("Avoid TTTT (4+ consecutive T)", "Four or more consecutive thymines (TTTT) act as a transcription termination signal for RNA Polymerase III (U6/H1 promoters used for sgRNA expression). Truncated guide RNA = no editing. This is an absolute disqualification criterion.", "Zero TTTT runs in spacer sequence", "Brummelkamp TR et al. Science 296:550-553, 2002. Doench 2016.") }

    // Spacer length
    if rule == "spacer_length" { return grule("Standard spacer length is 20 nt", "The canonical spacer length for SpCas9 is 20 nucleotides. Truncated guides (17-18 nt) can improve specificity by reducing off-target binding but may decrease on-target activity. Extended guides (21-22 nt) do not improve activity and are often processed back to 20 nt.", "20 nt for SpCas9, 23 nt for Cas12a", "Fu Y et al. Nat Biotechnol 32:279-284, 2014 (truncated guides).") }

    // Seed region: PAM-proximal mismatches are lethal to activity
    if rule == "seed_region" { return grule("Seed region sensitivity (8-12 nt PAM-proximal)", "The 8-12 nucleotides immediately adjacent to the PAM (the seed region) are critical for target recognition. Mismatches in the seed region almost completely abolish binding and cleavage. Mismatches in positions 1-8 (PAM-distal) are better tolerated. Off-target analysis must weight seed mismatches heavily.", "Zero mismatches in seed region for on-target. Check all genomic sites with 0-3 seed mismatches for off-target.", "Hsu PD et al. Nat Biotechnol 31:827-832, 2013. Doench 2016.") }

    // Avoid homopolymer runs
    if rule == "no_homopolymers" { return grule("Avoid homopolymer runs", "Avoid runs of 4+ identical bases (AAAA, CCCC, GGGG in addition to TTTT). Homopolymers reduce synthesis quality, can cause polymerase slippage, and correlate with reduced editing efficiency.", "No runs of 4+ identical nucleotides", "Doench 2016.") }

    // G at position 20 (PAM-proximal) preferred
    if rule == "position_20_g" { return grule("Prefer G at position 20 (PAM-proximal)", "A guanine at the PAM-proximal position (position 20 of the 20 nt spacer) is associated with higher on-target activity. This is one of the strongest single-nucleotide predictors of guide efficacy from the Doench 2016 model.", "G at position 20", "Doench JG et al. Nat Biotechnol 34:184-191, 2016.") }

    // Avoid G at position 1 (PAM-distal) for U6 promoter
    if rule == "position_1" { return grule("Position 1 considerations for U6 expression", "If using U6 promoter (most common), transcription initiates at G. A G at position 1 of the spacer ensures full-length transcript. If position 1 is not G, add an extra G (21 nt guide) or use H1 promoter (initiates at A). Does not apply to synthetic/RNP delivery.", "G at position 1 for U6 promoter expression", "Doench 2016.") }

    return grule("", "", "", "")
}

fn grna_design_rule_count() -> Int {
    return 7
}

// ═══════════════════════════════════════════════════════
// OFF-TARGET SCORING
// ═══════════════════════════════════════════════════════
//
// Off-target cleavage is the principal safety concern of
// CRISPR therapeutics. Mismatches in the seed region
// (PAM-proximal 8-12 nt) are far more disruptive than
// PAM-distal mismatches. This scoring function implements
// the positional weighting from Hsu et al. 2013.

fn off_target_score(mismatches: Int, pam_proximal_mismatches: Int) -> OffTargetResult {
    // Scoring: each mismatch reduces activity. PAM-proximal mismatches
    // carry 3-5x higher penalty than PAM-distal mismatches.
    // Score range: 0.0 (no off-target risk) to 1.0 (identical to on-target)

    // Perfect match at off-target site = maximum risk
    if mismatches == 0 { return otresult(1.0, "CRITICAL: Perfect match at off-target locus. Will be cleaved at near on-target efficiency. Redesign guide immediately.") }

    // One mismatch
    if mismatches == 1 {
        if pam_proximal_mismatches == 1 { return otresult(0.15, "Low off-target risk. Single seed mismatch strongly inhibits binding. Tolerable if no better guide available.") }
        if pam_proximal_mismatches == 0 { return otresult(0.60, "ELEVATED: PAM-distal mismatch partially tolerated. Cas9 can still bind and cleave at reduced efficiency. Validate by GUIDE-seq or CIRCLE-seq.") }
    }

    // Two mismatches
    if mismatches == 2 {
        if pam_proximal_mismatches == 2 { return otresult(0.02, "Negligible off-target risk. Two seed mismatches virtually abolish binding.") }
        if pam_proximal_mismatches == 1 { return otresult(0.08, "Very low off-target risk. One seed + one distal mismatch. Acceptable for most applications.") }
        if pam_proximal_mismatches == 0 { return otresult(0.35, "MODERATE: Two PAM-distal mismatches can still permit low-level cleavage. Consider high-fidelity Cas9 variants (eSpCas9, HiFi Cas9).") }
    }

    // Three mismatches
    if mismatches == 3 {
        if pam_proximal_mismatches >= 2 { return otresult(0.01, "Negligible. Three mismatches with two or more in seed region. Off-target cleavage extremely unlikely.") }
        if pam_proximal_mismatches == 1 { return otresult(0.05, "Very low risk. Three total mismatches with one in seed.") }
        if pam_proximal_mismatches == 0 { return otresult(0.15, "Low but detectable. Three PAM-distal mismatches. High-fidelity Cas9 recommended.") }
    }

    // Four or more mismatches: generally safe
    if mismatches >= 4 { return otresult(0.005, "Negligible. Four or more mismatches. Off-target cleavage below detection limits of standard assays.") }

    return otresult(0.0, "Unable to score. Check inputs.")
}

// ═══════════════════════════════════════════════════════
// ON-TARGET SCORING FEATURES (Doench 2016 model)
// ═══════════════════════════════════════════════════════
//
// The Rule Set 2 model from Doench 2016 identified sequence
// features at specific positions that predict on-target
// activity. These are the empirically strongest features
// from genome-wide CRISPR screens.

fn on_target_feature(feature: String) -> OnTargetFeature {
    if feature == "pos20_G" { return otfeature("Guanine at position 20", "Position 20 (PAM-proximal)", "G strongly preferred", "Highest single-position predictor of activity. G at pos 20 increases on-target cleavage. Possibly stabilizes R-loop formation near PAM.", "Doench JG et al. Nat Biotechnol 34:184-191, 2016.") }

    if feature == "pos16_not_G" { return otfeature("Avoid G at position 16", "Position 16", "A, C, or T preferred over G", "G at position 16 negatively correlates with activity in the Doench 2016 dataset. Mechanism uncertain.", "Doench 2016.") }

    if feature == "pos3_not_C" { return otfeature("Avoid C at position 3", "Position 3 (PAM-distal)", "A, G, or T preferred over C", "C at position 3 is the strongest negative single-nucleotide feature. May affect initial guide-DNA breathing at the PAM-distal end.", "Doench 2016.") }

    if feature == "gc_window" { return otfeature("GC content in last 6 nt (positions 15-20)", "Positions 15-20 (PAM-proximal 6 nt)", "At least 2 G/C in last 6 nt", "Moderate GC in seed region ensures stable R-loop nucleation. Too low = weak binding. Too high = off-target tolerance.", "Doench 2016.") }

    if feature == "dinuc_GG_20" { return otfeature("GG dinucleotide at positions 19-20", "Positions 19-20", "GG preferred", "The GG dinucleotide immediately upstream of the NGG PAM is the strongest positive dinucleotide feature. Creates effective NGGG motif.", "Doench 2016.") }

    if feature == "pos1_G" { return otfeature("G at position 1 for transcription initiation", "Position 1 (PAM-distal, 5-prime of spacer)", "G preferred for U6 expression", "Ensures full-length sgRNA transcript from U6 promoter. Not relevant for synthetic/RNP delivery.", "Doench 2016.") }

    if feature == "central_GC" { return otfeature("Moderate GC in central region (positions 8-14)", "Positions 8-14 (mid-spacer)", "Balanced GC (40-60%)", "Central region GC affects R-loop propagation rate. Too stable = mismatch-tolerant. Too weak = incomplete R-loop.", "Doench 2016.") }

    if feature == "pos2_not_T" { return otfeature("Avoid T at position 2", "Position 2", "A, G, or C preferred", "T at position 2 is a moderate negative predictor. May affect initial spacer-DNA pairing.", "Doench 2016.") }

    return otfeature("", "", "", "", "")
}

fn on_target_feature_count() -> Int {
    return 8
}

// ═══════════════════════════════════════════════════════
// DELIVERY METHODS
// ═══════════════════════════════════════════════════════
//
// The best editor in the world is useless if you cannot
// get it into the right cells. Delivery is the bottleneck
// of gene therapy. Each method trades off between
// packaging capacity, tissue tropism, immunogenicity,
// duration of expression, and clinical feasibility.

fn delivery_method(name: String) -> DeliveryMethod {
    // AAV: adeno-associated virus
    if name == "AAV" { return dmethod("Adeno-associated virus (AAV)", "Recombinant AAV packages transgene between ITRs. Infects target cells via receptor-mediated endocytosis. Episomal persistence (does not integrate). Multiple serotypes determine tissue tropism: AAV1 (muscle), AAV2 (broad/retina), AAV5 (lung/CNS), AAV8 (liver), AAV9 (CNS/heart, crosses BBB). ssDNA genome converted to dsDNA by host.", "4.7 kb (including ITRs, promoter, polyA). SpCas9 + guide exceeds limit. SaCas9 fits. Dual-AAV split-intein strategies for SpCas9.", "In vivo delivery to specific tissues. Long-term expression from episome. Low immunogenicity (relative). Multiple serotypes for tissue targeting. Established clinical manufacturing.", "Small packaging capacity. Pre-existing neutralizing antibodies in ~40-70% of population (serotype-dependent). Cannot redose (anti-capsid immunity). Prolonged Cas expression increases off-target risk. High manufacturing cost.", "Luxturna (AAV2, RPE65, retinal dystrophy). Zolgensma (AAV9, SMN1, SMA). Multiple CRISPR-AAV programs in preclinical.", "Naso MF et al. BioDrugs 31:317-334, 2017. Wang D et al. Nat Rev Drug Discov 18:358-378, 2019.") }

    // LNP: lipid nanoparticles
    if name == "LNP" { return dmethod("Lipid nanoparticle (LNP)", "Ionizable lipid nanoparticles encapsulate mRNA (encoding Cas protein) and sgRNA. LNP fuses with endosomal membrane after endocytosis, releasing cargo to cytoplasm. mRNA translated to Cas protein, complexes with sgRNA, enters nucleus. Transient expression: mRNA degrades within 24-48 hours. Key lipid: ionizable cationic lipid (DLin-MC3-DMA or proprietary variants like ALC-0315 in Comirnaty).", "No hard limit (mRNA can be any length). Limited by LNP formation efficiency. Cas9 mRNA (~4.5 kb) + sgRNA routinely packaged. Prime editor mRNA (~6.3 kb) packaged with reduced efficiency.", "Transient expression (reduces off-targets). No integration risk. No pre-existing immunity. Redosable. Scalable manufacturing (proven by COVID mRNA vaccines). No viral components.", "Primarily targets liver (hepatocyte tropism via ApoE adsorption and LDLR uptake). Extrahepatic delivery is an active research frontier. Potential for immunogenicity of lipid components. Cold chain requirements.", "Intellia NTLA-2001 (Cas9 mRNA + TTR sgRNA in LNP, IV, transthyretin amyloidosis). Verve VERVE-101 (ABE mRNA + PCSK9 sgRNA in LNP, IV, familial hypercholesterolemia). COVID vaccines (Pfizer/BioNTech, Moderna) validated LNP platform.", "Cullis PR, Hope MJ. Mol Ther 25:1467-1475, 2017. Gillmore JD et al. N Engl J Med 385:493-502, 2021 (NTLA-2001).") }

    // Electroporation
    if name == "electroporation" { return dmethod("Electroporation", "Brief electrical pulses create transient pores in cell membrane, allowing direct entry of Cas9 protein, mRNA, or RNP into cytoplasm. Used exclusively ex vivo: cells harvested from patient, edited in lab, reinfused. Pulse parameters (voltage, duration, number) optimized per cell type. Nucleofection (Lonza) is electroporation variant optimized for primary cells.", "No limit (direct physical delivery). Can deliver RNP, mRNA, plasmid, or protein of any size.", "Highest editing efficiency (often >90% for RNP). No viral vector. No immune response to delivery vehicle. Works for all cell types ex vivo. Immediate delivery (no expression delay with RNP).", "Ex vivo only. Cannot reach cells in vivo. Significant cell death (typically 20-40% viability loss). Requires cell harvest, culture, and reinfusion infrastructure. Cost and complexity of manufacturing.", "Casgevy (ex vivo electroporation of Cas9 RNP into CD34+ HSPCs). All CAR-T manufacturing. Ex vivo gene editing of T cells, HSPCs, iPSCs.", "Rols MP. Biochim Biophys Acta 1758:423-428, 2006.") }

    // RNP: ribonucleoprotein complex
    if name == "RNP" { return dmethod("Ribonucleoprotein (RNP)", "Pre-assembled complex of purified Cas protein + synthetic sgRNA delivered directly to cells. No nucleic acid encoding Cas is introduced. Protein acts immediately upon nuclear entry. Degraded by cellular proteases within 12-24 hours. Truly transient: shortest exposure window of any delivery method.", "Not applicable (protein delivered directly). Limited by delivery method used to get RNP into cells (electroporation, lipofection, microinjection).", "Fastest editing (no transcription/translation delay). Shortest Cas exposure (12-24 hours, minimizes off-targets). No risk of genomic integration of Cas gene. No immune response to viral DNA. Defined stoichiometry.", "Requires purified protein manufacturing (cost). Large protein-RNA complex (~160 kDa for SpCas9) has limited cell penetration without delivery aid. Primarily used with electroporation ex vivo. In vivo RNP delivery via LNP or cell-penetrating peptides is emerging.", "Standard of care for ex vivo editing. Casgevy uses RNP. Most academic CRISPR experiments. IDT and Synthego supply research-grade RNP components.", "Kim S et al. Genome Res 24:1012-1019, 2014.") }

    return dmethod("", "", "", "", "", "", "")
}

fn delivery_method_count() -> Int {
    return 4
}

// ═══════════════════════════════════════════════════════
// CLINICAL APPLICATIONS
// ═══════════════════════════════════════════════════════
//
// CRISPR has moved from bench to bedside. Casgevy was the
// first CRISPR therapy approved by any regulatory authority
// (MHRA Nov 2023, FDA Dec 2023). The pipeline is exploding.

fn clinical_trial(name: String) -> ClinicalTrial {
    // Casgevy: THE FIRST. Sickle cell disease and beta-thalassemia.
    if name == "casgevy_scd" { return ctrial("Exagamglogene autotemcel", "Casgevy", "BCL11A erythroid enhancer", "SpCas9 (ex vivo, RNP, electroporation into CD34+ HSPCs)", "Sickle cell disease (severe)", "Vertex Pharmaceuticals / CRISPR Therapeutics", "FDA approved December 8, 2023. MHRA approved November 16, 2023. First CRISPR therapy approved worldwide.", "BCL11A is a transcriptional repressor that silences fetal hemoglobin (HbF) after birth. CRISPR disrupts the erythroid-specific enhancer of BCL11A in patient HSPCs. With BCL11A knocked down, HbF is reactivated. HbF (alpha2/gamma2) does not sickle. Patients receive myeloablative busulfan conditioning, then reinfusion of edited HSPCs. Clinical results: 29/31 patients vaso-occlusive crisis-free at 12 months post-infusion.", "Frangoul H et al. N Engl J Med 384:252-260, 2021 (CLIMB SCD-121 trial).") }

    if name == "casgevy_thal" { return ctrial("Exagamglogene autotemcel", "Casgevy", "BCL11A erythroid enhancer", "SpCas9 (ex vivo, RNP, electroporation into CD34+ HSPCs)", "Transfusion-dependent beta-thalassemia (TDT)", "Vertex / CRISPR Therapeutics", "FDA approved January 2024 for TDT.", "Same mechanism as SCD: BCL11A enhancer disruption reactivates HbF. In beta-thalassemia, deficient beta-globin production causes severe anemia requiring chronic transfusions. HbF reactivation compensates for deficient adult hemoglobin. Clinical results: 42/44 patients transfusion-free at 12 months.", "Frangoul H et al. N Engl J Med 384:252-260, 2021 (CLIMB THAL-111 trial).") }

    // Intellia: in vivo LNP delivery to liver
    if name == "ntla2001" { return ctrial("NTLA-2001", "N/A (investigational)", "TTR (transthyretin)", "SpCas9 mRNA + sgRNA in LNP (IV infusion, in vivo)", "Hereditary transthyretin amyloidosis (hATTR) with polyneuropathy", "Intellia Therapeutics", "Phase III (MAGNITUDE trial). First in vivo CRISPR editing in humans (2021). Breakthrough Therapy Designation.", "Single IV infusion of LNP containing Cas9 mRNA and TTR-targeting sgRNA. LNP delivers to hepatocytes via LDLR pathway. Cas9 disrupts TTR gene, reducing production of misfolded transthyretin protein that causes systemic amyloid deposits. Dose-dependent TTR reduction: up to 93% reduction at 28 days. Durable: sustained reduction at 2+ years.", "Gillmore JD et al. N Engl J Med 385:493-502, 2021.") }

    // Intellia: hereditary angioedema
    if name == "ntla2002" { return ctrial("NTLA-2002", "N/A (investigational)", "KLKB1 (kallikrein B1, prekallikrein)", "SpCas9 mRNA + sgRNA in LNP (IV infusion, in vivo)", "Hereditary angioedema (HAE)", "Intellia Therapeutics", "Phase III. Fast Track Designation.", "Single IV infusion. LNP delivers to hepatocytes. Cas9 disrupts KLKB1 gene, reducing plasma prekallikrein. Prekallikrein is cleaved to kallikrein, which generates bradykinin, causing HAE attacks (swelling of skin, mucosa, airways). Reducing kallikrein = fewer/no attacks. Clinical results: 95% reduction in attack rate at highest dose. Potential one-and-done cure.", "Longhurst HJ et al. N Engl J Med 2024 (interim data).") }

    // CAR-T with CRISPR
    if name == "cart_crispr" { return ctrial("CTX110 (allogeneic CAR-T)", "N/A (investigational)", "TRAC (T-cell receptor alpha) and B2M (beta-2 microglobulin)", "SpCas9 (ex vivo editing of donor T cells)", "Relapsed/refractory B-cell malignancies (CD19+)", "CRISPR Therapeutics", "Phase I/II (CARBON trial).", "CRISPR used to create universal (allogeneic) CAR-T cells from healthy donor T cells. Cas9 knocks out TRAC (eliminates endogenous TCR, prevents graft-vs-host disease) and B2M (eliminates MHC-I, prevents host rejection). Anti-CD19 CAR inserted at TRAC locus via AAV6 HDR template. Off-the-shelf product: no need for patient-specific manufacturing. Addresses autologous CAR-T manufacturing bottleneck.", "CRISPR Therapeutics pipeline. Depil S et al. Nat Rev Drug Discov 19:185-199, 2020 (allogeneic CAR-T review).") }

    // Verve: base editing for cardiovascular disease
    if name == "verve101" { return ctrial("VERVE-101", "N/A (investigational)", "PCSK9 (proprotein convertase subtilisin/kexin type 9)", "Adenine base editor (ABE) mRNA in LNP (IV infusion, in vivo)", "Heterozygous familial hypercholesterolemia (HeFH)", "Verve Therapeutics", "Phase Ib (heart-1 trial). First in vivo base editing in humans (2022).", "Single IV infusion of LNP containing ABE mRNA and PCSK9-targeting sgRNA. ABE introduces A-to-G edit in PCSK9 gene in hepatocytes, creating a splice site mutation that permanently reduces PCSK9 protein production. PCSK9 normally degrades LDL receptors; reducing PCSK9 increases LDL receptor density on hepatocytes, lowering LDL cholesterol. Mimics naturally occurring PCSK9 loss-of-function mutations found in humans with lifelong low LDL and 88% reduced coronary heart disease risk.", "Musunuru K et al. Nature 593:429-434, 2021 (preclinical NHP data).") }

    return ctrial("", "", "", "", "", "", "", "", "")
}

fn clinical_trial_count() -> Int {
    return 7
}

// ═══════════════════════════════════════════════════════
// DNA REPAIR PATHWAYS
// ═══════════════════════════════════════════════════════
//
// What happens AFTER Cas9 cuts is entirely up to the cell.
// The editing outcome depends on which repair pathway the
// cell uses. Understanding repair is understanding CRISPR.

fn dna_repair(pathway: String) -> RepairPathway {
    // NHEJ: the default, error-prone pathway
    if pathway == "NHEJ" { return rpathway("NHEJ", "Non-homologous end joining", "Ku70/Ku80 heterodimer binds broken DNA ends within seconds. Recruits DNA-PKcs (DNA-dependent protein kinase catalytic subunit). End processing by Artemis nuclease (removes damaged/incompatible overhangs). Gap filling by pol mu/pol lambda (template-independent, error-prone). Ligation by XRCC4-Ligase IV-XLF complex. Fast (30 min to 2 hours). Does NOT require homologous template.", "Error-prone. Introduces small insertions and deletions (indels) of 1-20 bp at the cut site. Indels at coding exons cause frameshifts and premature stop codons = gene knockout. The basis of all CRISPR knockout experiments.", "High (dominant pathway, active in all cell cycle phases). ~70-90% of DSB repair uses NHEJ.", "All phases (G1, S, G2, M). Dominant in non-dividing cells.", "Ku70 (XRCC6, P12956), Ku80 (XRCC5, P13010), DNA-PKcs (PRKDC, P78527), Artemis (DCLRE1C, Q96SD1), XRCC4 (Q13426), DNA Ligase IV (LIG4, P49917), XLF/Cernunnos (NHEJ1, Q9H9Q4)", "Gene knockout. Disruption of regulatory elements (BCL11A enhancer in Casgevy). Creating frameshift mutations. Any application where precise sequence outcome is not required.", "Lieber MR. Annu Rev Biochem 79:181-211, 2010.") }

    // HDR: template-directed, precise but inefficient
    if pathway == "HDR" { return rpathway("HDR", "Homology-directed repair", "Requires homologous DNA template (sister chromatid or exogenous donor). End resection by MRN complex (Mre11-Rad50-Nbs1) + CtIP generates 3-prime ssDNA overhangs. RPA coats ssDNA. BRCA2 loads RAD51 recombinase onto ssDNA, displacing RPA. RAD51 filament invades homologous template, forming D-loop. DNA synthesis copies template sequence. Resolution of Holliday junctions or SDSA (synthesis-dependent strand annealing). Precise: copies donor template exactly.", "High fidelity. Copies donor template sequence precisely. Enables exact nucleotide changes, insertions of transgenes at specific loci (knock-in), and correction of disease mutations to wild-type sequence.", "Low (5-50% of editing outcomes, highly cell-type dependent). Restricted to S/G2 phases when sister chromatid is available. Competes with faster NHEJ. Efficiency improved by: NHEJ inhibitors (M3814, NU7441), cell cycle synchronization, optimized donor design (ssDNA donors better than dsDNA for small edits).", "S and G2 phases only. Absent in post-mitotic cells (neurons, cardiomyocytes). Major limitation for in vivo gene correction.", "MRN complex (MRE11A P49959, RAD50 Q92878, NBN O60934), CtIP (RBBP8, Q99708), RPA (P27694), BRCA2 (P51587), RAD51 (Q06609)", "Precise gene correction (correcting point mutations). Knock-in of transgenes at safe harbor loci (AAVS1, ROSA26). Tagging endogenous genes with fluorescent proteins. Creating specific disease models. Therapeutic gene correction (research stage, low efficiency limits clinical use).", "Jasin M, Rothstein R. Cold Spring Harb Perspect Biol 5:a012740, 2013.") }

    // MMEJ / alt-EJ: the middle ground
    if pathway == "MMEJ" { return rpathway("MMEJ", "Microhomology-mediated end joining (alternative end joining, alt-EJ)", "Uses 2-25 bp microhomologies flanking the DSB for alignment. End resection by MRN/CtIP (limited, unlike HDR). Microhomology search and annealing. Flap removal. Gap filling by Pol theta (POLQ, the hallmark polymerase of MMEJ). Ligation by Ligase III/XRCC1 or Ligase I. Results in predictable deletions defined by the microhomology positions.", "Moderate. Predictable deletions (defined by flanking microhomologies). More precise than NHEJ (outcomes can be predicted from sequence). Less precise than HDR (cannot introduce arbitrary sequences). Often creates in-frame deletions rather than frameshifts.", "Moderate (10-30% of repair outcomes). Active when NHEJ is impaired. More frequent in cancer cells (often NHEJ-deficient). Can be promoted by NHEJ inhibition.", "S and G2 (partially), some activity in G1. Less cell-cycle restricted than HDR.", "Pol theta (POLQ, Q9Y253), PARP1 (P09874), Ligase III (LIG3, P49916), XRCC1 (P18887), MRN complex, CtIP", "Predictable gene editing (MMEJ-based precise editing tools like MHCUT). Template-free precise deletions. Used when HDR template delivery is impractical but specific outcomes are needed.", "Sfeir A, Symington LS. Trends Biochem Sci 40:701-714, 2015. Seol JH et al. Cell Rep 24:3377-3387, 2018.") }

    return rpathway("", "", "", "", "", "", "", "", "")
}

fn dna_repair_count() -> Int {
    return 3
}

// ═══════════════════════════════════════════════════════
// UTILITY FUNCTIONS
// ═══════════════════════════════════════════════════════

fn is_dna_targeting(name: String) -> Bool {
    let v = cas_variant(name)
    return v.target_type == "DNA"
}

fn is_rna_targeting(name: String) -> Bool {
    let v = cas_variant(name)
    return v.target_type == "RNA"
}

fn is_dsb_free(name: String) -> Bool {
    // Base editors and prime editors do not create double-strand breaks
    if name == "CBE" { return true }
    if name == "ABE" { return true }
    if name == "PE" { return true }
    return false
}

fn fits_aav(name: String) -> Bool {
    // Returns true if the Cas variant fits in a single AAV vector
    if name == "SaCas9" { return true }
    if name == "Cas13d" { return true }
    return false
}

fn pam_for(name: String) -> String {
    let v = cas_variant(name)
    return v.pam_sequence
}

fn nobel_prize_year() -> Int {
    // Doudna and Charpentier, Nobel Prize in Chemistry
    return 2020
}

fn first_crispr_therapy_approval() -> String {
    return "Casgevy (exagamglogene autotemcel). MHRA approved November 16, 2023. FDA approved December 8, 2023. First CRISPR-based therapy approved for human use."
}
