#!/usr/bin/env python3
"""
build_lattice_assemblies.py

Generates per-folio Markdown "lattice grid view" combining:
- Image reference (Beinecke scan path)
- IVTFF text per line
- Per-token segmentation chips with FSM-class tag, meaning, lineage tier
- Section register identification
- Volvelle/dial cross-references
- Conciliator + corpus citations
- Anchor words (lattice label list and F-247 six)

Output: ../../../resources/tools/provenance/index.html#s-73c6480f4fa9a561[N][rv].md (one per folio)
"""

import json, re, os, sys
from pathlib import Path
from collections import defaultdict, Counter

sys.path.insert(0, '../../../resources/readers/provenance/source-88ca8a9b1aabc6c8.html')
import anchor_lists  # noqa: E402 — P01 (2026-09-28): both anchor lists + section renderer

# ─── PATHS ───
PILE_PATH    = '../../../resources/readers/provenance/source-e6f95f8ac3e90f2b.html'
IVTFF_PATH   = 'c7ffff9e1f3ecbec174e234c.txt'
FOLIO_MAPS   = Path('../../../resources/readers/provenance/source-7282075282d0eea3.html')
IMAGES_DIR   = Path('../../../resources/readers/provenance/source-8fd15a718d00aa9f.html')
OUT_DIR      = Path('../../../resources/readers/provenance/source-67a34d1930f7dad1.html')

OUT_DIR.mkdir(parents=True, exist_ok=True)

# ─── LOAD PILE ───
with open(PILE_PATH) as f:
    PILE_DOC = json.load(f)
PILE = {k: v for k, v in PILE_DOC['stems'].items() if not k.startswith('_')}

# ─── LOAD IVTFF ───
with open(IVTFF_PATH) as f:
    IVTFF = f.read()

# ZL-parsed pages, keyed by folio, for the anchor-words section (P01, 2026-09-28). Independent of
# this module's own (narrower) folio-discovery regex below.
ZL_PAGES, _ZL_ORDER = anchor_lists.parse()

# ─── CONSTANTS / FRAMEWORK ───
SECTIONS = {
    'herbal':   (1, 66),
    'astro':    (67, 74),
    'balne':    (75, 84),
    'rosette':  (85, 86),
    'pharma':   (87, 102),
    'recipes':  (103, 116),
}

# P01 (2026-09-28): the chip marker (★lattice label list★) flags membership in the lattice label
# list only. F-247 membership is reported in the anchor-words section, not on chips.
CROSS_SECTION_ANCHORS = anchor_lists.LATTICE_LABEL_LIST
CONVENTION_IV_LABELS = {
    'd': 'decoctio (cooking)',
    'e': 'electuarium (compound prep)',
    'p': 'pulvis (powder) / pi (Greek)',
    'r': 'radix (root)',
    's': 'syrupus (syrup)',
    'f': 'fiat / phi (Greek)',
    'm': 'misce (mix) / mu (Greek)',
    'l': 'lohoch / lambda (Greek)',
    'o': 'oleum (oil) / omicron (Greek)',
    'y': 'Greek-prefix class qualifier (yerapigra/ydromel/yriaca)',
}

GREEK_NUMERAL = {
    'o': 70, 'l': 30, 'd': 4, 'r': 100, 'v': 400, 'x': 600,
    'k': 20, 'm': 40, 'f': 500, 'p': 80, 't': 300,
    'I': 10, 'i': 10, 'c': 200, 's': 200, 'a': 1, 'e': 5,
    'n': 50, 'h': 8, 'g': 3, 'b': 2, 'y': 400,
}

DIAL_TARGETS = {
    17: 'f57v 17-slot Greek alphabet+numeral key',
    19: 'Metonic 19-year cycle (f70v2 figures-with-stars)',
    20: 'Theophilus 20-color uroscopy wheel (Conciliator-attested)',
    21: 'Fasciculus Medicinae 21-matula uroscopy wheel',
    28: 'lunar mansions',
    30: 'lunar month / zodiac wheel nymphs',
    7:  'planetary days',
    12: 'zodiac signs',
    8:  'cardinal directions / wind rose',
    4:  'matula vessel sections / temperaments',
}

# The rosettes central page is keyed fRos in ZL, with no folio number; it sits on the 85v/86r
# foldout side (TP-001, 2026-10-07). Before this, the f\d+ regexes skipped it and f85r2's block
# ran on into fRos's header comments.
FOLIO_NUM_OVERRIDE = {'fRos': 86}
FOLIO_IMAGE_OVERRIDE = {'fRos': '0157_85v_and_86r__foldout_.jpg'}

# ─── HELPERS ───

def section_for(fnum):
    for sec, (lo, hi) in SECTIONS.items():
        if lo <= fnum <= hi: return sec
    return 'other'

def js_clean(raw):
    cleaned = raw
    def pick(m):
        a, b = m.group(1), m.group(2)
        return b if '?' in a and '?' not in b else a
    cleaned = re.sub(r'\[([^:\]]+):([^\]]+)\]', pick, cleaned)
    cleaned = re.sub(r'\[([^\]]+)\]', r'\1', cleaned)
    cleaned = re.sub(r'\{([^}]*)\}', r'\1', cleaned)
    cleaned = re.sub(r'<[^>]*>|[<>%$!?]|[\d;]', '', cleaned).replace(',','').strip("' ").strip()
    return cleaned

def js_tokenize(text):
    def protect(m): return m.group(0).replace('.','\x01').replace(',','\x02').replace('-','\x03')
    p = re.sub(r'\[[^\]]*\]', protect, text)
    p = re.sub(r'\{[^}]*\}', protect, p)
    parts = re.split(r'[.,]+', p)
    return [pp.replace('\x01','.').replace('\x02',',').replace('\x03','-') for pp in parts if pp.strip()]

def segment(tok):
    """Longest-match segmentation against PILE. Returns list of (text, pile_entry_or_None)."""
    segs=[]; i=0
    while i<len(tok):
        hit=None
        for length in range(min(15, len(tok)-i), 0, -1):
            s=tok[i:i+length]
            if s in PILE:
                hit=(s,PILE[s]); i+=length; break
        if not hit:
            if segs and segs[-1][1] is None:
                segs[-1]=(segs[-1][0]+tok[i],None)
            else:
                segs.append((tok[i],None))
            i+=1
        else:
            segs.append(hit)
    return segs

def chip_label(meaning):
    if not meaning: return '?'
    fsm = re.search(r'\[(?:[a-z@]+-?)\]=([^\s\[]+)', meaning)
    if fsm: return fsm.group(1).replace('(','').replace(')','')
    return re.split(r'[\s\(\—]', meaning)[0].replace('(','').replace(')','')

def lineage_badge(entry):
    lin = entry.get('_lineage', '')
    if 'corridor' in lin: return '★'
    if 'falsified' in lin: return '✗'
    if lin == 'Honeycutt Ai Labs-substrate': return '●'
    if 'INTERNAL' in lin: return '·'
    return '?'

def class_opener_meaning(c):
    return CONVENTION_IV_LABELS.get(c, f'{c}-class')

# ─── PER-FOLIO ASSEMBLY ───

def assemble_folio(folio):
    """Produce the assembly markdown for one folio."""
    fnum_match = re.search(r'\d+', folio)
    if not fnum_match and folio not in FOLIO_NUM_OVERRIDE: return None
    fnum = FOLIO_NUM_OVERRIDE.get(folio) or int(fnum_match.group())
    section = section_for(fnum)

    # Pull this folio's IVTFF lines + header notes
    folio_pat = rf'<{folio}>(.+?)(?=<f(?:\d+[rv][12]?|Ros)>|\Z)'
    m = re.search(folio_pat, IVTFF, re.DOTALL)
    if not m: return None
    block = m.group(0)

    # Header IVTFF flags + comments
    header_flags = ''
    comment_lines = []
    for ln in block.split('\n'):
        if ln.startswith(f'<{folio}>'):
            header_flags = ln.replace(f'<{folio}>', '').strip()
        elif ln.startswith('#'):
            comment_lines.append(ln.lstrip('#').strip())

    # Find image
    img_files = [IMAGES_DIR / FOLIO_IMAGE_OVERRIDE[folio]] if folio in FOLIO_IMAGE_OVERRIDE else sorted(IMAGES_DIR.glob(f'*_{folio[1:]}*.jpg'))
    if not img_files:
        # Sub-foldout folios (f70v1, f72r3, f86v4 ...) have no image named for the sub-folio.
        # Section audit 2026-09-30: fall back to the folio_substrate row's image_path (read-only).
        try:
            import sqlite3
            _c = sqlite3.connect('file:../../../resources/tools/substrate/index.html?mode=ro', uri=True)
            _r = _c.execute('select image_path from folio_substrate where folio_id=?', (folio,)).fetchone()
            _c.close()
            if _r and _r[0] and os.path.exists(_r[0]):
                img_files = [Path(_r[0])]
        except Exception:
            pass
    img_path = str(img_files[0]) if img_files else f'(no image found for {folio})'

    # Find folio_map raw.json
    raw_json_path = FOLIO_MAPS / f'{folio}.raw.json'
    has_raw = raw_json_path.exists()

    # Star markers in this folio
    star_lines = [ln for ln in block.split('\n') if ln.lstrip().startswith('#') and re.search(r'\bstars?\b', ln.lower())]  # section audit 2026-09-30: whole-word match, the bare substring caught "starts"/"start" (f1r)
    star_count_estimates = []
    for sl in star_lines:
        for m in re.findall(r'(\d+)\s*star', sl, re.IGNORECASE):
            star_count_estimates.append(int(m))

    # Tokenize and segment all lines
    line_re = re.compile(rf'<{folio}\.(\d+),([^>]*)>\s+(.+)')
    line_records = []  # list of (locus, flag, raw, tokens_with_chips)
    class_opener_freq = Counter()
    paragraph_starts = []
    label_lines = []
    total_tokens = 0
    matched_tokens = 0
    tier_counts = Counter()

    for ln in block.split('\n'):
        m2 = line_re.match(ln)
        if not m2: continue
        lineno, flag, raw = m2.groups()
        is_label = 'L' in flag
        is_para_start = (flag.startswith('@') and 'P' in flag) or '<%>' in raw  # 2026-09-30: `<%>` is the IVTFF paragraph marker (285 over f103r-f116r); the flag alone gave one PARA-START per folio

        parts = js_tokenize(raw)
        chips = []
        first_class_letter = None
        for p in parts:
            cleaned = js_clean(p)
            if not cleaned or cleaned.startswith('@'): continue
            total_tokens += 1
            segs = segment(cleaned)

            if first_class_letter is None and cleaned:
                first_class_letter = cleaned[0]

            # Build chip representation
            if len(segs) == 1 and segs[0][1] is not None:
                # One chip, full match
                entry = segs[0][1]
                badge = lineage_badge(entry)
                cls = chip_label(entry.get('meaning', ''))
                chips.append({
                    'token': cleaned,
                    'chip_text': f'{badge}{cleaned}={cls}',
                    'meaning': entry.get('meaning', '')[:200],
                    'tier': entry.get('_lineage', ''),
                    'is_anchor': cleaned in CROSS_SECTION_ANCHORS,
                })
                matched_tokens += 1
                tier_counts[entry.get('_lineage', '')] += 1
            else:
                # Multi-segment fallback (shouldn't happen with full pile)
                pieces = '|'.join([f'{s[0]}' if s[1] else f'?{s[0]}' for s in segs])
                chips.append({
                    'token': cleaned,
                    'chip_text': f'·{cleaned}=[{pieces}]',
                    'meaning': '',
                    'tier': '',
                    'is_anchor': False,
                })

        if first_class_letter:
            class_opener_freq[first_class_letter] += 1
        if is_para_start:
            paragraph_starts.append((lineno, parts[0] if parts else ''))
        if is_label:
            label_lines.append((lineno, raw))
        line_records.append({
            'locus': f'{folio}.{lineno}',
            'flag': flag,
            'raw': raw,
            'is_label': is_label,
            'is_para_start': is_para_start,
            'chips': chips,
        })

    # Dial correspondence: count of stars + class-opener distribution suggests dial address
    dial_matches = []
    for cnt in set(star_count_estimates):
        if cnt in DIAL_TARGETS:
            dial_matches.append((cnt, DIAL_TARGETS[cnt]))
    # Also: if folio has period-17 ring (slot count = 17), mark that
    n_labels = len(label_lines)
    if n_labels in DIAL_TARGETS:
        dial_matches.append((n_labels, f'label count = {DIAL_TARGETS[n_labels]}'))

    # Conciliator-corpus citations applicable to this folio
    corpus_cites = []
    if section in ('balne', 'pharma', 'recipes'):
        corpus_cites.append({
            'cite': 'Pietro d Abano Conciliator',
            'path': '839def1e832bc2605e83360f.txt',
            'relevance': 'integrating reference; trine/aspect/uroscopy/conditional-dose'
        })
    if section in ('herbal',):
        corpus_cites.append({
            'cite': 'Dioscorides Longobardus (BAV Cod.Lat.Mon.337)',
            'path': '84a86361d15731ff82c4310c.txt',
            'relevance': 'plant-class enumeration + Greek pharmacology'
        })
        corpus_cites.append({
            'cite': 'Leiden VLQ 9 — Pseudo-Apuleius Herbarium (6th c. Italy)',
            'path': '../../../resources/readers/provenance/source-d5c522e753b78f8f.html',
            'relevance': 'pre-Salernitan herbal-illustration tradition; 69 plant+snake illustrations; direct ancestor of Western herbal layout'
        })
    if section == 'pharma' or section == 'recipes':
        corpus_cites.append({
            'cite': 'Galen Opera (Yale)',
            'path': 'dc364e061fab7baac1bd5723.txt',
            'relevance': 'dose-by-strength conditional + decoctio + pulvis preparation'
        })
        corpus_cites.append({
            'cite': 'Saladino Compendium Aromatariorum (1488 Ferrara)',
            'path': 'ac6cbf3720e7ba99018e9170.txt',
            'relevance': 'y-class corpus referents (yerapigra/yriaca/ydromel/yeradiacolloquintidos), drachma=3-figure, six-slot recipe grammar'
        })
    if section == 'astro':
        corpus_cites.append({
            'cite': 'Pal.lat.1373 Prosdocimo de Beldomandi Compositio astrolabii',
            'path': '../../../resources/readers/provenance/source-290893d04a984d82.html',
            'relevance': 'Padua astrolabe: solar longitude → ascendens; altitude → almucantar → time'
        })
    if 67 <= fnum <= 73:
        corpus_cites.append({
            'cite': 'Tur 2022 + BnF Latin 7478 fol 14D Salernitan zodiac melothesia',
            'path': '../../../resources/readers/provenance/source-293234866a95a13e.html',
            'relevance': 'per-sign body-part assignments + treatment prescriptions'
        })
    # f57v Theophilus 20-color uroscopy comparators
    if folio.startswith('f57v') or folio.startswith('f67') or folio.startswith('f68') or folio.startswith('f57r'):
        corpus_cites.append({
            'cite': 'Wellcome MS 83 (b18935473) — incomplete Articella, mid-14c',
            'path': '../../../resources/tools/provenance/index.html#s-25f5f493a2d90bcf',
            'relevance': 'carries Theophilus De urinis (ff.4r-10v) + Expositio terminorum glossary (ff.31r-32v) — direct y-class lemma source + 20-color uroscopy primary witness'
        })
        corpus_cites.append({
            'cite': 'Wellcome MS.82 (b18935576) — Articella + Secreta Secretorum, early 14c',
            'path': '../../../resources/tools/provenance/index.html#s-b08c6c3b2105ef88',
            'relevance': 'full 9-tract Articella incl. Theophilus De urinis + Pseudo-Aristotle Secreta Secretorum extract; second independent witness for f57v 20-color comparison'
        })
        corpus_cites.append({
            'cite': 'BAV Pal.lat.1115 ff.161v-163v — Theophilus De urinis (HTR-validated 2026-04-27)',
            'path': '../../../resources/tools/provenance/index.html#s-710266cfb6784665',
            'relevance': 'Pal.lat.1115 carries Theophilus tract; opening dedication "ad domnum suum gloriosum regem charissimum" confirmed via HTR'
        })

    # Build the markdown
    md = []
    md.append(f'# {folio} — Lattice Assembly')
    md.append('')
    md.append(f'**Section:** `{section}` | **Folio number:** {fnum}')
    md.append('')
    if header_flags: md.append(f'**IVTFF header:** `{header_flags}`')
    md.append(f'**Image:** `{img_path}`')
    md.append(f'**Folio map:** `{raw_json_path}` ({"present" if has_raw else "absent"})')
    md.append('')
    md.append('## Comments / illustration notes (from IVTFF)')
    if comment_lines:
        for c in comment_lines:
            md.append(f'- {c}')
    else:
        md.append('- (none)')
    md.append('')
    md.append('## Coverage stats')
    md.append(f'- Total tokens: {total_tokens}')
    md.append(f'- Matched against pile: {matched_tokens} ({100*matched_tokens/total_tokens:.1f}%)' if total_tokens else '- (no tokens)')
    md.append(f'- Tier distribution: {dict(tier_counts)}')
    md.append('')
    md.append('## Class-opener frequency by line (FSM register)')
    if class_opener_freq:
        for c, n in class_opener_freq.most_common():
            md.append(f'- `{c}-` ({n}×) — {class_opener_meaning(c)}')
    md.append('')

    if star_lines:
        md.append('## Star-marker notes')
        for sl in star_lines[:15]:
            md.append(f'- {sl.lstrip("#").strip()}')
        if star_count_estimates:
            md.append(f'- **Star count estimates:** {sorted(set(star_count_estimates))}')
        md.append('')

    if dial_matches:
        md.append('## Volvelle / dial cross-references')
        for cnt, desc in dial_matches:
            md.append(f'- **{cnt} → {desc}**')
        md.append('')

    zl_page = ZL_PAGES.get(folio)
    if zl_page is not None:
        md.append(anchor_lists.render_anchor_section(zl_page['lines']))
        md.append('')

    if corpus_cites:
        md.append('## Corpus citations applicable to this folio')
        for c in corpus_cites:
            md.append(f'- **{c["cite"]}** — {c["relevance"]}')
            md.append(f'  - Path: `{c["path"]}`')
        md.append('')

    md.append('## Lattice grid — line-by-line chip rendering')
    md.append('')
    for rec in line_records:
        kind_marker = '[LABEL]' if rec['is_label'] else ('[PARA-START]' if rec['is_para_start'] else '[para-cont]')
        md.append(f'### `{rec["locus"]}` {kind_marker} (`{rec["flag"]}`)')
        md.append(f'**raw:** `{rec["raw"]}`')
        if rec['chips']:
            md.append('')
            md.append('| chip | meaning | tier |')
            md.append('|---|---|---|')
            for ch in rec['chips']:
                anchor_mark = ' **★lattice label list★**' if ch['is_anchor'] else ''
                meaning = ch['meaning'].replace('|', '\\|')[:120]
                tier = ch['tier'].replace('Honeycutt Ai Labs-', '')
                md.append(f'| `{ch["chip_text"]}`{anchor_mark} | {meaning} | {tier} |')
            md.append('')
        else:
            md.append('(no tokens)')
            md.append('')

    md.append('---')
    md.append(f'*Generated by build_lattice_assemblies.py — pile v{PILE_DOC.get("version","?")}*')
    return '\n'.join(md)

# ─── SUBSTRATE EVIDENCE BLOCK PRESERVATION (added 2026-09-08) ───
# This builder deliberately does not read the substrate findings DB. The
# per-folio SUBSTRATE EVIDENCE block is rendered separately by
# ../../../resources/tools/provenance/index.html#s-c6dd4b829775f655
# A rebuild must not silently destroy it, so any existing block is carried
# forward verbatim. Re-run the renderer afterwards to refresh it against the DB.

SUB_EV_BEGIN = '<!-- SUBSTRATE-EVIDENCE:BEGIN -->'
SUB_EV_END   = '<!-- SUBSTRATE-EVIDENCE:END -->'
SUB_EV_RE = re.compile(re.escape(SUB_EV_BEGIN) + r'.*?' + re.escape(SUB_EV_END), re.S)


def carry_forward_substrate_block(out_path, md):
    """Re-attach the substrate evidence block from the file being overwritten."""
    if not out_path.exists():
        return md
    try:
        prev = out_path.read_text(encoding='utf-8')
    except Exception:
        return md
    m = SUB_EV_RE.search(prev)
    if not m:
        return md
    return md.rstrip('\n') + '\n\n' + m.group(0) + '\n'


# ─── BATCH GENERATE ───


def main():
    # Discover all folios in IVTFF
    folio_pattern = re.compile(r'^<(f(?:\d+[rv][12]?|Ros))>', re.MULTILINE)
    folios = sorted(set(folio_pattern.findall(IVTFF)),
                    key=lambda f: (FOLIO_NUM_OVERRIDE.get(f) or int(re.search(r'\d+', f).group()), f))
    print(f'Discovered {len(folios)} folios in IVTFF')

    written = 0; failed = 0
    for folio in folios:
        try:
            md = assemble_folio(folio)
            if md is None:
                failed += 1
                continue
            out_path = OUT_DIR / f'{folio}.md'
            md = carry_forward_substrate_block(out_path, md)
            with open(out_path, 'w') as f:
                f.write(md)
            written += 1
        except Exception as e:
            print(f'  FAIL {folio}: {e}')
            failed += 1
    print(f'Wrote {written} per-folio assemblies; {failed} failures')
    print('Substrate evidence blocks were carried forward verbatim. To refresh them '
          'against the findings DB, run:\n'
          '  python3 ../../../resources/tools/provenance/index.html#s-660f3b2cfa6e60bc')
    return written, failed

if __name__ == '__main__':
    main()
