#!/usr/bin/env python3
from __future__ import annotations
import re, sqlite3, sys
from pathlib import Path

DB_PATH = '../../../resources/tools/substrate/index.html'
THIS_PATH = 'b9de2d995629345fceeb3867.py'

GENERIC_FIRST_NAMES = {
    'jean','pierre','guillaume','jacques','nicolas','jacquot','jeanne','henri',
    'thibaut','etienne','gilles','jacqueline','marie','margaret','anne',
    'catherine','agnes','abraham','philippe','john','philip','william','adolph',
    'renier','robin','martin','alain','colinet','guillemin','humbert','huguenin',
    'the bedford master',
}
ALT_STOPWORDS = {
    'duke','master','michel','michels','[...]','...','margaret of burgundy',
}

DISTINCTIVE_TITLE_SUBSTRINGS = {
  "Wroclaw M 1302": [
    "Codex Salernitanus"
  ],
  "SBB Lat. quart. 674": [
    "Lat. quart. 674",
    "Lat quart 674"
  ],
  "Heidelberg Cpg 214": [
    "Cpg 214",
    "Cpg214",
    "Speyrer Arzneibuch"
  ],
  "Wolfsthurn Sternbach Ms. 1": [
    "Wolfsthurn",
    "Sternbach"
  ],
  "SBB Mgf 928": [
    "Mgf 928",
    "Mgf928"
  ],
  "SBB Mgf 1069": [
    "Mgf 1069",
    "Mgf1069"
  ],
  "Yale Cushing/Whitney MS 10": [
    "Cushing/Whitney MS 10",
    "Yale Cushing",
    "Frugardi"
  ],
  "BL Royal 12 E VIII": [
    "Royal 12 E VIII",
    "BL Royal 12"
  ],
  "Bodleian Digby 69": [
    "Digby 69"
  ],
  "BSB Clm 405": [
    "Clm 405",
    "Clm405"
  ],
  "BL Harley 3": [
    "BL Harley 3",
    "Harley MS 3",
    "Mirfield"
  ],
  "SBB Lat. fol. 88": [
    "Lat. fol. 88",
    "Lat fol 88"
  ],
  "Ghent UB Hs. 444": [
    "Hs. 444",
    "Hs 444",
    "Vrouwen heimlicheit"
  ],
  "BSB Cgm 261": [
    "Cgm 261",
    "Cgm261"
  ],
  "Cambridge Trinity R.15.21": [
    "Trinity R.15.21",
    "R.15.21",
    "Foxton",
    "Liber Cosmographiae"
  ],
  "Augsburg UB III.2.8 34": [
    "III.2.8 34"
  ],
  "Prague NK XXIII F 29": [
    "XXIII F 29",
    "Prague NK XXIII"
  ],
  "2002046": [
    "2002046",
    "Beinecke MS 408",
    "MS 408"
  ]
}

DISTINCTIVE_TITLE_SUBSTRINGS.update({
  "Alberti_De_Componendis_Cifris_1568_Aldine": [
    "De Componendis Cifris",
    "Alberti 1568"
  ],
  "BJ_Krakow_NDIGORP000800": [
    "NDIGORP000800",
    "BJ Krakow"
  ],
  "BL_Cotton_Galba_E_IV": [
    "Cotton Galba E IV",
    "Galba E IV"
  ],
  "BL_Egerton_2020_Carrara_Herbal": [
    "Egerton 2020",
    "Carrara Herbal"
  ],
  "BL_Egerton_747": [
    "Egerton 747"
  ],
  "BL_Harley_2897_Breviary": [
    "Harley 2897"
  ],
  "BL_Harley_3407_via_Wayback": [
    "Harley 3407"
  ],
  "BL_Harley_3747_via_Wayback": [
    "Harley 3747"
  ],
  "BL_Harley_3799_Despars": [
    "Harley 3799"
  ],
  "BL_Harley_3894_via_Wayback": [
    "Harley 3894"
  ],
  "BL_Harley_4114_Despars_Avicenna_1486": [
    "Harley 4114"
  ],
  "BL_Harley_4166_via_Wayback": [
    "Harley 4166"
  ],
  "BL_Harley_5218_via_Wayback": [
    "Harley 5218"
  ],
  "BL_Sloane_4016": [
    "Sloane 4016"
  ],
  "Battisti_1984_Le_Macchine_Cifrate_Giovanni_Fontana": [
    "Le Macchine Cifrate",
    "Battisti 1984"
  ],
  "BnF_Lat_6823_Manfredus": [
    "BnF Lat 6823",
    "BnF Lat. 6823",
    "Lat 6823",
    "Manfredus"
  ],
  "BnF_Lat_6915_Despars": [
    "BnF Lat 6915",
    "Lat 6915"
  ],
  "BnF_Lat_6926_Despars": [
    "BnF Lat 6926",
    "Lat 6926"
  ],
  "BnF_Lat_6927_Despars": [
    "BnF Lat 6927",
    "Lat 6927"
  ],
  "BnF_Lat_6928_Despars": [
    "BnF Lat 6928",
    "Lat 6928"
  ],
  "BnF_Lat_6937_Despars": [
    "BnF Lat 6937",
    "Lat 6937"
  ],
  "BnF_Lat_7295_Arnaut": [
    "BnF Lat 7295",
    "BnF Lat. 7295",
    "Lat 7295",
    "Lat. 7295"
  ],
  "BnF_Lat_7418_Florilegium_Italicum": [
    "BnF Lat 7418",
    "Lat 7418",
    "MS 7418",
    "Florilegium italicum"
  ],
  "bnf_Lat_7418": [
    "BnF Lat 7418",
    "Lat 7418",
    "MS 7418"
  ],
  "Bologna_Aldrovandi_153": [
    "Aldrovandi 153",
    "Bologna Aldrovandi"
  ]
})

DISTINCTIVE_TITLE_SUBSTRINGS.update({
  "CPP_28_Medical_Botany_William_Woodville": [
    "Medical Botany",
    "Woodville"
  ],
  "CPP_29_Buch_der_Cirurgia_Hieronymus_Brunschwig": [
    "Buch der Cirurgia",
    "Brunschwig"
  ],
  "CPP_32_Illustrations_of_Medical_Botany_Joseph_Carson": [
    "Joseph Carson"
  ],
  "CPP_35_Le_Grant_Herbier": [
    "Le Grant Herbier",
    "Grant Herbier"
  ],
  "CPP_37_Pestbuch_Hieronymus_Brunschwig": [
    "Pestbuch"
  ],
  "CPP_3_Images_from_Les_Oeuvres_d_Ambroise_Par_eacute_": [
    "Ambroise Pare",
    "Ambroise Paré"
  ],
  "CPP_6_Under_the_Influence_of_the_Heavens": [
    "Under the Influence of the Heavens"
  ],
  "Gallica_Vigenere_1586_TraicteDesChiffres": [
    "Vigenere 1586",
    "Vigenère 1586",
    "Vigenere",
    "Vigenère"
  ],
  "HD_Pal_lat_1298": [
    "Pal.lat.1298",
    "Pal lat 1298"
  ],
  "HD_Pal_lat_1362b": [
    "Pal.lat.1362b",
    "Pal lat 1362b"
  ],
  "HD_Pal_lat_1368": [
    "Pal.lat.1368",
    "Pal lat 1368"
  ],
  "LJS_449_UPenn_Schoenberg_1446": [
    "LJS 449",
    "Schoenberg 449"
  ],
  "LoC_Hartlieb_1462": [
    "LoC Hartlieb 1462",
    "Hartlieb 1462"
  ],
  "Lyon_1498_Despars_Avicenna": [
    "Lyon 1498"
  ],
  "MDZ_Bede_Clm_14725": [
    "Clm 14725"
  ],
  "MDZ_Hermannus_Clm_14836": [
    "Clm 14836"
  ],
  "MSS_Barb.lat.160": [
    "Barb.lat.160",
    "Barb lat 160"
  ],
  "MSS_Barb.lat.186": [
    "Barb.lat.186",
    "Barb lat 186"
  ],
  "MSS_Leiden_VLQ9": [
    "Leiden VLQ9",
    "VLQ9"
  ],
  "MSS_Pal.lat.1115": [
    "Pal.lat.1115"
  ],
  "MSS_Pal.lat.1221": [
    "Pal.lat.1221"
  ],
  "MSS_Pal.lat.1229": [
    "Pal.lat.1229"
  ],
  "MSS_Pal.lat.1262": [
    "Pal.lat.1262"
  ],
  "MSS_Pal.lat.1268": [
    "Pal.lat.1268"
  ],
  "MSS_Pal.lat.1373": [
    "Pal.lat.1373",
    "Pal lat 1373"
  ],
  "MSS_Vienna_Dioscorides_Med_Gr_1": [
    "Vienna Dioscorides",
    "Med. Gr. 1",
    "Med Gr 1"
  ],
  "MSS_Wellcome_MS82": [
    "Wellcome MS82",
    "Wellcome MS 82"
  ],
  "MSS_Wellcome_MS83": [
    "Wellcome MS83",
    "Wellcome MS 83"
  ]
})

DISTINCTIVE_TITLE_SUBSTRINGS.update({
  "MS_Chantilly_Tres_Riches_Heures": [
    "Tres Riches Heures",
    "Très Riches Heures"
  ],
  "MS_Florence_BML_Plut_73_16": [
    "Plut. 73.16",
    "Plut 73 16",
    "Plut.73.16"
  ],
  "MS_Heidelberg_Cpg311_Hartlieb": [
    "Cpg 311",
    "Cpg311"
  ],
  "MS_Padua_OrtoBotanico_Ar26": [
    "Ar26",
    "Ar 26",
    "OrtoBotanico"
  ],
  "MS_Princeton_Augsburg_Kastner_1452": [
    "Princeton Kastner",
    "Kastner 1452"
  ],
  "MS_Tuebingen_Md2": [
    "Tuebingen Md2",
    "Tübingen Md2"
  ],
  "Morgan_B12_England_1425_Computus": [
    "Morgan B12",
    "Morgan MS B.12"
  ],
  "Morgan_B21_Norwich_Medical_1400": [
    "Morgan B21",
    "Morgan MS B.21"
  ],
  "Morgan_B27_German_Medical_Astronomical_1450": [
    "Morgan B27",
    "Morgan MS B.27"
  ],
  "Morgan_B28_German_Calendar_1458": [
    "Morgan B28",
    "Morgan MS B.28"
  ],
  "Morgan_G47_Doctors_Folding_Almanac_1464": [
    "Morgan G47",
    "Morgan MS G.47"
  ],
  "Morgan_G74_DeBalneis_1400_SItaly": [
    "Morgan G74",
    "Morgan MS G.74",
    "DeBalneis"
  ],
  "Morgan_M139_Columella_Milan_1469": [
    "Morgan M139",
    "Morgan MS M.139"
  ],
  "Morgan_M165_Aldobrandino_Regimen_1440": [
    "Morgan M165",
    "Morgan MS M.165",
    "M.165",
    "Aldobrandino"
  ],
  "Morgan_M180_Padua_GospelLectionary_1436": [
    "Morgan M180",
    "Morgan MS M.180"
  ],
  "Morgan_M509_dAbano_Charles_VIII_1490": [
    "Morgan M509",
    "Morgan MS M.509"
  ],
  "Morgan_M693_Avicenna_Italian_1300": [
    "Morgan M693",
    "Morgan MS M.693"
  ],
  "Morgan_M858_Aristotle_Padua_1250": [
    "Morgan M858",
    "Morgan MS M.858"
  ],
  "Morgan_M925_Italian_Computus_1018_FLAGGED": [
    "Morgan M925",
    "Morgan MS M.925"
  ],
  "Morgan_M941_Almanac_VeinMan_1433": [
    "Morgan M941",
    "Morgan MS M.941"
  ],
  "ONB_Cod_5315": [
    "Cod. 5315",
    "Cod 5315"
  ],
  "Trithemius_1518_Polygraphiae_first_edition": [
    "Trithemius 1518",
    "Polygraphiae",
    "Trithemius"
  ],
  "Vat.lat.3245_humanist_Cicero": [
    "Vat.lat.3245",
    "Vat lat 3245"
  ],
  "Vat_lat_2462": [
    "Vat.lat.2462",
    "Vat lat 2462"
  ],
  "Vat_lat_6973": [
    "Vat.lat.6973",
    "Vat lat 6973"
  ],
  "Vat_lat_6974": [
    "Vat.lat.6974",
    "Vat lat 6974"
  ],
  "Wellcome_MS16_Albicus_Geismar1422": [
    "Wellcome MS 16",
    "Wellcome MS16",
    "Henricus de Geismar"
  ],
  "Wolfenbuttel_HAB_79Aug2_Hartlieb": [
    "Cod. 79 Aug. 2",
    "79 Aug 2",
    "Wolfenbuttel"
  ],
  "btv1b100331057": [
    "btv1b100331057",
    "NAL 635",
    "Secretum de thesauro"
  ],
  "btv1b52513793d": [
    "btv1b52513793d"
  ],
  "btv1b9066197g": [
    "btv1b9066197g"
  ],
  "Wellcome_b18771531": [
    "Wellcome b18771531",
    "b18771531"
  ],
  "Wellcome_b19672676": [
    "Wellcome b19672676",
    "b19672676"
  ],
  "BnF_NAL_635_Fontana_Secretum": [
    "NAL 635",
    "Secretum de thesauro",
    "BnF NAL 635"
  ]
})

def load_figures(con):
    rows = []
    for r in con.execute('SELECT id, name, name_alts FROM figures').fetchall():
        names = [r[1].strip()]
        if r[2]:
            for alt in r[2].split(','):
                a = alt.strip()
                if a and a.lower() not in ALT_STOPWORDS:
                    names.append(a)
        names = [n for n in names if not (
            n.lower() in GENERIC_FIRST_NAMES or
            (len(n.split()) == 1 and len(n) < 5)
        )]
        if names:
            rows.append({'id': r[0], 'names': names, 'primary': r[1]})
    return rows


def load_manuscripts(con):
    rows = []
    for r in con.execute('SELECT id, shelfmark, title FROM manuscripts').fetchall():
        subs = DISTINCTIVE_TITLE_SUBSTRINGS.get(r[1], [])
        cand = [r[1]] + subs
        seen, out_list = set(), []
        for c in cand:
            if c and c.lower() not in seen:
                seen.add(c.lower())
                out_list.append(c)
        rows.append({'id': r[0], 'shelfmark': r[1], 'title': r[2] or '', 'matchers': out_list})
    return rows


def compile_matcher(s):
    esc = re.escape(s)
    esc = esc.replace(chr(92)+' ', chr(92)+'s+')
    if re.search('[A-Za-z0-9]$', s) and re.search('^[A-Za-z0-9]', s):
        pat = '(?<![A-Za-z0-9_])' + esc + '(?![A-Za-z0-9_])'
    else:
        pat = esc
    return re.compile(pat, re.IGNORECASE)


def context_window(text, m, half=50):
    s = max(0, m.start() - half)
    e = min(len(text), m.end() + half)
    snip = text[s:e].replace(chr(10), ' ').replace(chr(34), chr(39)).strip()
    if s > 0:
        snip = '...' + snip
    if e < len(text):
        snip = snip + '...'
    return snip[:160]


def main():
    con = sqlite3.connect(DB_PATH)
    cur = con.cursor()
    deleted = cur.execute('DELETE FROM relationships WHERE source_path = ?', (THIS_PATH,)).rowcount
    print('deleted', deleted, 'prior phase-6 edges')
    figures = load_figures(con)
    manuscripts = load_manuscripts(con)
    print('loaded', len(figures), 'figures,', len(manuscripts), 'manuscripts')
    fig_patterns = []
    for f in figures:
        for n in f['names']:
            fig_patterns.append((f['id'], f['primary'], n, compile_matcher(n)))
    ms_patterns = []
    for m in manuscripts:
        for s in m['matchers']:
            ms_patterns.append((m['id'], m['shelfmark'], s, compile_matcher(s)))
    print('compiled', len(fig_patterns), 'figure matchers,', len(ms_patterns), 'manuscript matchers')
    findings = cur.execute("SELECT id, code, title, COALESCE(notes,''), COALESCE(working_file,'') FROM findings").fetchall()
    fig_edges = 0
    ms_edges = 0
    findings_scanned = 0
    files_read = 0
    files_missing = 0
    seen_files = {}
    for fid, fcode, ftitle, fnotes, fwf in findings:
        findings_scanned += 1
        blobs = [('title', ftitle or ''), ('notes', fnotes or '')]
        if fwf:
            if fwf not in seen_files:
                p = Path(fwf)
                if p.exists() and p.is_file():
                    try:
                        seen_files[fwf] = p.read_text(errors='replace')
                        files_read += 1
                    except OSError:
                        seen_files[fwf] = None
                        files_missing += 1
                else:
                    seen_files[fwf] = None
                    files_missing += 1
            wf_text = seen_files.get(fwf)
            if wf_text is not None:
                blobs.append(('working_file', wf_text))
        seen_fig = {}
        seen_ms = {}
        for field, text in blobs:
            if not text:
                continue
            for fig_id, primary, name, pat in fig_patterns:
                if fig_id in seen_fig:
                    continue
                mm = pat.search(text)
                if mm:
                    seen_fig[fig_id] = (name, field, context_window(text, mm))
            for ms_id, shelfmark, src, pat in ms_patterns:
                if ms_id in seen_ms:
                    continue
                mm = pat.search(text)
                if mm:
                    seen_ms[ms_id] = (src, field, context_window(text, mm))
        for fig_id, (matched, field, ctx) in seen_fig.items():
            note = 'matched ' + repr(matched) + ' in ' + field + '; ctx: ' + repr(ctx)
            cur.execute(
                "INSERT INTO relationships "
                "(from_entity_type, from_entity_id, to_entity_type, to_entity_id, "
                " relation_type, source_path, notes) "
                "VALUES ('finding', ?, 'figure', ?, 'discusses-figure', ?, ?)",
                (fid, fig_id, THIS_PATH, note)
            )
            fig_edges += 1
        for ms_id, (matched, field, ctx) in seen_ms.items():
            note = 'matched ' + repr(matched) + ' in ' + field + '; ctx: ' + repr(ctx)
            cur.execute(
                "INSERT INTO relationships "
                "(from_entity_type, from_entity_id, to_entity_type, to_entity_id, "
                " relation_type, source_path, notes) "
                "VALUES ('finding', ?, 'manuscript', ?, 'cites-manuscript', ?, ?)",
                (fid, ms_id, THIS_PATH, note)
            )
            ms_edges += 1
    con.commit()
    con.close()
    print()
    print('=== phase-6 NER edge pass complete ===')
    print('  findings scanned:         ', findings_scanned)
    print('  working_file unique read: ', files_read)
    print('  working_file missing:     ', files_missing)
    print('  finding->figure edges:    ', fig_edges)
    print('  finding->manuscript edges:', ms_edges)
    print('  total edges emitted:      ', fig_edges + ms_edges)
    return 0


if __name__ == '__main__':
    sys.exit(main())
