#!/usr/bin/env python3
"""
Phase 1 substrate-DB repairs — 2026-05-12.
Bounded scope:
  (a) Fix 6 Pal.lat.* rows where date column = shelfmark number.
  (b) Fix #104 Wellcome_b18771531 source_path drift (was import-script path).
  (c) Quarantine 42 false-positive Myrepsus rels by flagging notes.
  (d) Insert Myrepsus figure + MS.MSL.134 + MS.MSL.60 + Q20 structural-match finding.
  (e) Insert canonical relationship edges + Q20 folio→manuscript edges + finding→folio edges.

Read-only verification at end. All writes in one transaction.
"""
import sqlite3, json, sys

DB = '../../../resources/tools/substrate/index.html'

con = sqlite3.connect(DB)
con.row_factory = sqlite3.Row
cur = con.cursor()

def counts(label):
    print(f"\n[{label}]")
    for t in ('figures','manuscripts','findings','axes','corridors','relationships','citations','folio_substrate','corpus_chunks'):
        cur.execute(f"SELECT COUNT(*) FROM {t}")
        print(f"  {t}: {cur.fetchone()[0]}")

counts("PRE-REPAIR")

cur.execute("BEGIN")

try:
    # --- (a) Pal.lat.* date-bug ---
    print("\n=== (a) Pal.lat.* date=shelfmark fix ===")
    pal_ids = [(62,'1115'),(63,'1221'),(64,'1229'),(65,'1262'),(66,'1268'),(67,'1373')]
    for mid, bad_date in pal_ids:
        r = cur.execute("SELECT shelfmark, date FROM manuscripts WHERE id=?",(mid,)).fetchone()
        if not r: continue
        if r['date'] == bad_date:
            cur.execute("""
                UPDATE manuscripts SET date='14th-15th c. (est., pending per-MS paleographic verification)',
                notes=COALESCE(notes||char(10),'') || '[2026-05-12 fix: date was wrongly set to shelfmark number ' || ? || '; corrected to estimated 14th-15th c.]',
                updated_at=CURRENT_TIMESTAMP
                WHERE id=?
            """, (bad_date, mid))
            print(f"  fixed id={mid} {r['shelfmark']}: '{bad_date}' -> '14th-15th c. (est.)'")
        else:
            print(f"  skipped id={mid} {r['shelfmark']}: date already '{r['date']}'")

    # --- (b) #104 source_path drift ---
    print("\n=== (b) #104 source_path drift ===")
    cur.execute("""
        UPDATE manuscripts SET source_path='../../../resources/readers/provenance/source-75d85e78bd07cdb9.html',
        notes=COALESCE(notes||char(10),'') || '[2026-05-12 fix: source_path was pointing at import_phase3_edges.py script; corrected to HTR output directory]',
        updated_at=CURRENT_TIMESTAMP
        WHERE id=104
    """)
    r=cur.execute("SELECT source_path FROM manuscripts WHERE id=104").fetchone()
    print(f"  id=104 source_path -> {r['source_path']}")

    # --- (c) Quarantine 42 false-positive Myrepsus rels ---
    print("\n=== (c) Quarantine false-positive Myrepsus rels ===")
    fp = cur.execute("""
        SELECT id FROM relationships
        WHERE (notes LIKE '%Myrepsus%' OR notes LIKE '%Myrepsos%' OR notes LIKE '%Dynameron%')
    """).fetchall()
    flag = '[NOTES-QUARANTINED 2026-05-12: false-positive NER context captured "Myrepsus Antidotarium" while edge actually points at BnF Lat 7418. Edge target is correct; notes context is misleading. Real Myrepsus rows now exist (MS.MSL.134 / MS.MSL.60) under separate edges.]' + chr(10) + '[orig-notes]: '
    for r in fp:
        cur.execute("UPDATE relationships SET notes=? || COALESCE(notes,'') WHERE id=?", (flag, r['id']))
    print(f"  flagged {len(fp)} rels")

    # --- (d) Insert Myrepsus triple + finding ---
    print("\n=== (d) Insert Myrepsus figure + 2 manuscripts + 1 finding ===")

    cur.execute("""
        INSERT INTO figures (name, name_alts, birth_year, death_year, region, role, source_path, status, notes)
        VALUES (?,?,?,?,?,?,?,?,?)
    """, (
        'Nicolaus Myrepsos',
        'Nicolaus Myrepsus, Nikolaos Myrepsos, Nicholas Myrepsos, Nicholas of Alexandria, Nikolaos of Nicaea, Niccolò Mirepso',
        1240, 1310,
        'Nicaea / Constantinople',
        'physician / apothecary',
        '../../../resources/tools/provenance/index.html#s-ca3bed5af9ce2efa',
        'imported',
        'Byzantine physician fl. c.1290. Author of the Dynameron, a Greek alphabetical formulary of over 2,500 polypharmacy recipes compiled from Greek+Latin+Arabic sources. Translated into Latin in the 14th c.; circulated widely until the 16th c. Sources: Wellcome catalogue records t6ns6qrh (MS.MSL.134 Latin Antidotarium) and fx5a4wg2 (MS.MSL.60 §3 Greek Dynameron table, ff.20-45). Finding-aid: Dawson 1932 Manuscripta medica.'
    ))
    myr_fig = cur.lastrowid
    print(f"  figure Nicolaus Myrepsos id={myr_fig}")

    cur.execute("""
        INSERT INTO manuscripts (shelfmark, title, date, language, contents_summary, provenance, image_paths_json, catalog_ids_json, source_path, status, notes)
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
    """, (
        'MS.MSL.134',
        'The Antidotarium of Nicolaus Myrepsus',
        '14th c.',
        'Latin',
        '68 folios, vellum, 8vo, 20.3x12.5 cm, modern binding. Neat uncial 14th-c. script with capitals in red. Latin translation of the alphabetical Antidotarium of Nicolaus Myrepsus of Nicaea, compiled from Greek+Latin+Arabic authors with over 2,500 recipes. Letters B/C/D/E have large elaborate initials; the rest have blanks left. Main text ends f63 with colophon "Antidotarium explicit feliciter. Amen." Addenda f63-64. 16th-c. annotations on f65v + f67v.',
        'Medical Society of London. Original ownership trail not documented in catalogue. Public Domain Mark.',
        json.dumps([
            "e0b09205b34724062afe97ad.pdf",
            "../../readers/97/979bf2b09824ba8d3bb0b4aa12caefb91f98c69fda8cc7c2d6c55d258689acd2.png",
            "../../../resources/tools/provenance/index.html#s-10d623c5ebedf3aa"
        ]),
        json.dumps({
            "Sierra":"b18749422",
            "Calm-RecordId":"9fabb6b9-4cf6-4f59-a8df-79b2a7c35bdc",
            "Calm-RefNo":"MSMSL134",
            "Calm-AltRefNo":"MS.MSL.134",
            "Wellcome-works-id":"t6ns6qrh",
            "Wellcome-digcode":"digwms",
            "METS":"b18749422",
            "IIIF-manifest":"https://iiif.wellcomecollection.org/presentation/v2/b18749422"
        }),
        '../../../resources/tools/provenance/index.html#s-ca3bed5af9ce2efa',
        'imported',
        '152 IIIF canvases; on-disk PDF is 153 pages (1 cover/flyleaf delta). Finding-aid: Warren R. Dawson, Manuscripta medica (London, 1932). Q20 recipe-quire structural-match anchor for VMS (Ed call 2026-05-12). Letter-rubric ordering at pp.46+137 is the prior comparator finding (closed 2026-05-06 COMPARATOR_QUEUE).'
    ))
    mssl134 = cur.lastrowid
    print(f"  manuscript MS.MSL.134 id={mssl134}")

    cur.execute("""
        INSERT INTO manuscripts (shelfmark, title, date, language, contents_summary, provenance, image_paths_json, catalog_ids_json, source_path, status, notes)
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
    """, (
        'MS.MSL.60',
        'Greek Medical Texts',
        'Early 15th century',
        'Greek',
        '221 folios, 8vo, 21.5x14 cm, early 18th-c. leather binding rebacked. Single early-15th-c. scribe (one secondary hand in §15). 43 catalogued sections / 40+ identified opuscula. §1-2 Hippocrates Aphorisms+Prognostics. §3 Table from Dynameron of Nicolaus Myrepsos (ff.20-45) - Greek-source formulary cross-referenced from MS.MSL.134. §8 alphabetical lexicon of materia medica compiled from all Greek writers (ff.48-50). §14 On the Twelve Precious Stones (lapidary, breastplate of Jewish highpriest). §15 Astrological formulae + 7-concentric-circle diagram in red. §17 Astrological diagrams + explanatory text. §18 Botanical list in 4 columns headed Syriac Names of Plants (f.71v). §20-21 lookup-table-of-treatises + treatises in head-to-foot order. §26 Simeon Seth On Foods (12th c. Greek+Persian+Arabic+Indian materia medica). §41 Theophilus On the Pulse. §42 Galen Euporista bk 1. §43 Hermes Trismegistos remedies for pains in the feet. Galen, Hippocrates, Theophilus, Paulus Aegineta, Aetius, Maximus Planudus, Stephanus, Demetrius Pepagomenos throughout. VMS-contemporary (early 15th c.).',
        'Originally in library of Anthony Askew. Lacks usual James Sims ownership note. Public Domain Mark.',
        json.dumps([
            "../../../resources/tools/provenance/index.html#s-1559f898e3a484ec",
            "https://iiif.wellcomecollection.org/image/b19683704_ms_msl_60_NNNN.JP2/"
        ]),
        json.dumps({
            "Sierra":"b19683704",
            "Calm-RecordId":"0472b1ea-bfa4-4f48-83f9-4710b873c5a3",
            "Calm-RefNo":"MSMSL60",
            "Calm-AltRefNo":"MS.MSL.60",
            "Wellcome-works-id":"fx5a4wg2",
            "Wellcome-digcode":"digwms,diggreek",
            "METS":"b19683704",
            "IIIF-manifest":"https://iiif.wellcomecollection.org/presentation/v2/b19683704"
        }),
        '../../../resources/tools/provenance/index.html#s-5cfd42c34ee8cec7',
        'imported',
        '466 IIIF canvases. Finding-aid: Warren R. Dawson, Manuscripta medica (London, 1932). VMS-relevant in 3 directions: (1) §3 ff.20-45 is the Greek-source Dynameron table - corridor anchor for Q20 recipe-quire structural-match; (2) §8 ff.48-50 alphabetical lexicon directly addresses f1r right-margin alphabet question + validates Greek-before-Latin search rule; (3) §18 f.71v botanical 4-column list of Syriac plant names is multi-column multi-script plant-name list - structurally parallel to Q20 recipe-quire density.'
    ))
    mssl60 = cur.lastrowid
    print(f"  manuscript MS.MSL.60 id={mssl60}")

    cur.execute("""
        INSERT INTO findings (code, title, status, confidence, axis_ids_json, working_file, source_path, notes)
        VALUES (?,?,?,?,?,?,?,?)
    """, (
        'F-MYREPSUS-DYNAMERON-Q20-RECIPE-PAGE-SHAPE-MATCH',
        'VMS Q20 recipe-quire structural-shape match to Nicolaus Myrepsos Dynameron polypharmacy page',
        'Supported',
        'Medium-High',
        '[]',
        '../../../resources/tools/provenance/index.html#s-78334da9f94d9bcf',
        '../../readers/97/979bf2b09824ba8d3bb0b4aa12caefb91f98c69fda8cc7c2d6c55d258689acd2.png',
        'Ed-identified 2026-05-12 from Wellcome MS.MSL.134 page 37 render: densely-packed comma-delimited ingredient lists with supralinear (interlinear) glosses + right-margin red rubric column + left-margin annotation strip - four-register page habit. Same structural shape on VMS Q20 (f103r-f116v). Greek-source anchor at MS.MSL.60 §3 (ff.20-45, table from Dynameron). The Dynameron contains over 2,500 polypharmacy recipes compiled from Greek+Latin+Arabic sources. DISTINCT from prior letter-rubric-ordering finding (2026-05-06 closed comparator at MS.MSL.134 pp.46+137 — that was about ordering; this is about page-habit / item-list-density / multi-register-gloss). References: Lane G audit 2026-05-12, COMPARATOR_QUEUE_2026-05-06.md, page_037_recipe_layer.png. Axis attachment pending - likely F-REGIMEN-STACK-N where polypharmacy / pharmacy-as-regimen-component sits.'
    ))
    myr_find = cur.lastrowid
    print(f"  finding F-MYREPSUS-DYNAMERON-Q20-RECIPE-PAGE-SHAPE-MATCH id={myr_find}")

    # --- (e) Canonical relationship edges ---
    print("\n=== (e) Canonical relationship edges ===")

    edges = [
        ('figure', myr_fig, 'manuscript', mssl134, 'text-attributed-to', '14th c. Latin translation of the Antidotarium'),
        ('figure', myr_fig, 'manuscript', mssl60, 'text-attributed-to', '§3 ff.20-45: table compiled from the Greek Dynameron'),
        ('manuscript', mssl134, 'manuscript', mssl60, 'related-holding', 'Wellcome catalogue cross-reference: MS.MSL.60 ff.20-45 cf. MS.No.134'),
        ('finding', myr_find, 'manuscript', mssl134, 'cites-manuscript', 'Primary structural-shape source: page 37 (rendered as page_037_recipe_layer.png) - four-register page habit'),
        ('finding', myr_find, 'manuscript', mssl60, 'cites-manuscript', 'Greek-source corroborating witness: §3 Dynameron table + §8 alphabetical lexicon + §18 4-column botanical list'),
        ('finding', myr_find, 'figure', myr_fig, 'discusses-figure', 'Subject of the structural-match: Nicolaus Myrepsos as Q20 recipe-quire shape comparator'),
    ]
    for fe,fi,te,ti,rt,nt in edges:
        cur.execute("""
            INSERT INTO relationships (from_entity_type, from_entity_id, to_entity_type, to_entity_id, relation_type, source_path, notes)
            VALUES (?,?,?,?,?,?,?)
        """, (fe,fi,te,ti,rt,'../../../resources/tools/provenance/index.html#s-00fefad76b93d2c5',nt))
    print(f"  inserted {len(edges)} canonical edges")

    # Q20 folios → MS.MSL.134 (compared-against, follows existing folio_substrate→manuscript pattern)
    q20_folios = ['f103r','f103v','f104r','f104v','f105r','f105v','f106r','f106v',
                  'f107r','f107v','f108r','f108v','f111r','f111v','f112r','f112v',
                  'f113r','f113v','f114r','f114v','f115r','f115v','f116r','f116v']
    f_to_ms_count = 0
    for fid in q20_folios:
        # verify folio exists
        r = cur.execute("SELECT folio_id FROM folio_substrate WHERE folio_id=?", (fid,)).fetchone()
        if not r:
            print(f"  WARN: folio_substrate row missing for {fid}; skipping")
            continue
        cur.execute("""
            INSERT INTO relationships (from_entity_type, from_entity_id, to_entity_type, to_entity_id, relation_type, source_path, notes)
            VALUES ('folio_substrate', ?, 'manuscript', ?, 'compared-against', ?, ?)
        """, (fid, mssl134, '../../../resources/tools/provenance/index.html#s-00fefad76b93d2c5',
              'Q20 recipe-quire folio compared against Myrepsus Antidotarium (MS.MSL.134) page-habit shape per F-MYREPSUS-DYNAMERON-Q20-RECIPE-PAGE-SHAPE-MATCH 2026-05-12'))
        f_to_ms_count += 1
    print(f"  inserted {f_to_ms_count} Q20-folio -> MS.MSL.134 'compared-against' edges")

    # Finding -> Q20 folios (discusses-folio)
    fd_count = 0
    for fid in q20_folios:
        r = cur.execute("SELECT folio_id FROM folio_substrate WHERE folio_id=?", (fid,)).fetchone()
        if not r: continue
        cur.execute("""
            INSERT INTO relationships (from_entity_type, from_entity_id, to_entity_type, to_entity_id, relation_type, source_path, notes)
            VALUES ('finding', ?, 'folio_substrate', ?, 'discusses-folio', ?, ?)
        """, (myr_find, fid, '../../../resources/tools/provenance/index.html#s-00fefad76b93d2c5',
              'F-MYREPSUS-DYNAMERON-Q20-RECIPE-PAGE-SHAPE-MATCH discusses Q20 recipe-quire folio'))
        fd_count += 1
    print(f"  inserted {fd_count} F-MYREPSUS -> Q20-folio 'discusses-folio' edges")

    # f1r -> MS.MSL.60 (compared-against, for the §8 alphabetical lexicon parallel)
    cur.execute("""
        INSERT INTO relationships (from_entity_type, from_entity_id, to_entity_type, to_entity_id, relation_type, source_path, notes)
        VALUES ('folio_substrate', 'f1r', 'manuscript', ?, 'compared-against', ?, ?)
    """, (mssl60, '../../../resources/tools/provenance/index.html#s-00fefad76b93d2c5',
          'f1r right-margin alphabet compared against MS.MSL.60 §8 alphabetical lexicon of materia medica (Greek-source ordering anchor)'))
    print("  inserted f1r -> MS.MSL.60 'compared-against' edge (alphabetical-lexicon anchor)")

    con.commit()
    print("\nCOMMIT successful")

except Exception as e:
    con.rollback()
    print(f"\nROLLBACK due to: {e}")
    sys.exit(1)

counts("POST-REPAIR")

# --- verification SELECTs ---
print("\n=== verification ===")
print("\nMyrepsus entities present:")
for row in cur.execute("SELECT 'figure' AS t, id, name AS label FROM figures WHERE name LIKE '%Myrepsos%' UNION ALL SELECT 'manuscript', id, shelfmark FROM manuscripts WHERE shelfmark IN ('MS.MSL.134','MS.MSL.60') UNION ALL SELECT 'finding', id, code FROM findings WHERE code='F-MYREPSUS-DYNAMERON-Q20-RECIPE-PAGE-SHAPE-MATCH'"):
    print(f"  {row['t']} id={row['id']} | {row['label']}")

print("\nMyrepsus-related rels:")
for row in cur.execute("""
    SELECT relation_type, COUNT(*) n FROM relationships
    WHERE (from_entity_type='figure' AND from_entity_id=(SELECT id FROM figures WHERE name LIKE '%Myrepsos%'))
       OR (to_entity_id IN (SELECT id FROM manuscripts WHERE shelfmark IN ('MS.MSL.134','MS.MSL.60')) AND to_entity_type='manuscript')
       OR (from_entity_type='finding' AND from_entity_id=(SELECT id FROM findings WHERE code='F-MYREPSUS-DYNAMERON-Q20-RECIPE-PAGE-SHAPE-MATCH'))
    GROUP BY relation_type
"""):
    print(f"  {row['relation_type']}: {row['n']}")

print("\nPal.lat.* date check:")
for row in cur.execute("SELECT id, shelfmark, date FROM manuscripts WHERE shelfmark LIKE '%Pal.lat.%' ORDER BY id"):
    print(f"  id={row['id']} {row['shelfmark']}: '{row['date']}'")

print("\n#104 verification:")
r = cur.execute("SELECT id, shelfmark, source_path FROM manuscripts WHERE id=104").fetchone()
print(f"  id={r['id']} {r['shelfmark']}: src={r['source_path']}")

print("\nQuarantined rels (sample):")
for row in cur.execute("SELECT id, substr(notes,1,80) AS n FROM relationships WHERE notes LIKE '%NOTES-QUARANTINED%' LIMIT 3"):
    print(f"  id={row['id']}: {row['n']}...")

con.close()
print("\n=== Phase 1 complete ===")
