#!/usr/bin/env python3
"""
GREEK ORDINAL / ROUND-9 GLYPH INVESTIGATION
=============================================
Ed's hypothesis: the VMS uses Greek-pattern ordinal addressing (α'=1, β'=2...θ'=9)
embedded in the notation. The "round-9" form (θ') = "ninth entry/category".

In IVTFF 2b encoding, the round-9 glyph candidate is {c@132;h} (Windows-1252 char 132
= „ = double low-9 quotation mark, U+201E). c@133 (Windows-1252 = … horizontal ellipsis)
appears to co-occur closely with c@132.

Tests:
  1. All c@NNN occurrences: position within paragraph, folio, section
  2. Are c@132/c@133 a BRACKET PAIR or independent markers?
  3. Inter-occurrence spacing within same folio: regular interval = ordinal spacing
  4. Content between bracket pairs: is it consistent (same length/type)?
  5. Distribution across sections: concentrated in pharma-recipes (breviarium format)?
  6. Comparison to known theta/9 positions: do inline occurrences correspond to
     expected ordinal indices in recipe sequence?
"""

import re, csv
from collections import defaultdict, Counter

IVTFF = 'c7ffff9e1f3ecbec174e234c.txt'
CSV   = '../../../resources/readers/provenance/source-42f53525071b6eb1.html'
OUT   = 'ae90143a7a80f69dbf790267.txt'

# ── Load section map ─────────────────────────────────────────────────────────
folio_section = {}
with open(CSV) as fh:
    for row in csv.DictReader(fh):
        folio_section[row['folio_id']] = row['section']

# ── Parse IVTFF: collect ALL c@NNN occurrences ──────────────────────────────
line_re  = re.compile(r'^<(f[\w.]+),([^>]+)>\s*(.*)')
cnum_re  = re.compile(r'\{c@(\d+);(\w+)\}')
cnum_any = re.compile(r'\{c@\d+[;,][^}]*\}')

def clean_tok(raw):
    """Clean a raw token to EVA, handling all IVTFF escapes."""
    raw = re.sub(r'\{c@\d+;(\w+)\}', r'\1', raw)
    raw = re.sub(r'\{(\w+)\}', r'\1', raw)
    raw = re.sub(r'\[([^:]+):[^\]]+\]', r'\1', raw)
    raw = re.sub(r'<%>|<[^>]+>', '', raw)
    return re.sub(r'[^a-zA-Z]', '', raw).lower()

def tokenize_preserving_cnums(text):
    """
    Tokenize text but preserve {c@NNN} as special tokens 'CNUM_NNN'.
    Returns list of (cleaned_token, is_cnum, cnum_value).
    """
    # Insert spaces around c@NNN placeholders so they separate cleanly from adjacent chars
    marked = re.sub(r'\{c@(\d+);[^}]*\}', r' __CNUM_\1__ ', text)
    # Remove @NNN; inline glyph refs (not the c@NNN form; these are visual variants)
    marked = re.sub(r'@\d+;', ' ', marked)
    # Remove other IVTFF tags
    marked = re.sub(r'<[^>]+>', ' ', marked)
    tokens = []
    for part in re.split(r'[.,\s]+', marked):
        if not part: continue
        if part.startswith('__CNUM_') and part.endswith('__'):
            num = part[7:-2]
            try:
                tokens.append(('CNUM_' + num, True, int(num)))
            except ValueError:
                pass
        else:
            cleaned = clean_tok(part)
            if cleaned:
                tokens.append((cleaned, False, None))
    return tokens

# Collect: for each c@NNN occurrence, record:
#   (cnum_val, folio, section, marker_type, para_pos, token_context)
occurrences = []

# Also track paragraph-level token sequences to determine para_pos
current_folio  = None
current_marker = None
current_tokens = []  # list of (tok, is_cnum, cnum_val)

def flush_para(folio, marker, tokens):
    """Process a completed paragraph, recording all c@NNN positions."""
    if not folio or not tokens: return
    base = re.sub(r'\.\d+$', '', folio)
    sec  = folio_section.get(base, '')
    for i, (tok, is_cnum, cnum_val) in enumerate(tokens):
        if is_cnum:
            # Get surrounding context
            ctx_start = max(0, i-3)
            ctx_end   = min(len(tokens), i+4)
            ctx = ' '.join(t[0] for t in tokens[ctx_start:ctx_end])
            occurrences.append({
                'cnum': cnum_val,
                'folio': base,
                'section': sec,
                'marker': marker,
                'para_pos': i,
                'para_len': len(tokens),
                'context': ctx,
            })

with open(IVTFF, encoding='utf-8', errors='replace') as fh:
    for line in fh:
        m = line_re.match(line.rstrip())
        if not m: continue
        fid, marker, text = m.group(1), m.group(2), m.group(3)
        base = re.sub(r'\.\d+$', '', fid)

        toks = tokenize_preserving_cnums(text)

        if '@P' in marker or '@L' in marker or '@R' in marker or '@C' in marker:
            flush_para(current_folio, current_marker, current_tokens)
            current_folio  = base
            current_marker = marker
            current_tokens = toks[:]
        elif '+P' in marker and base == current_folio:
            current_tokens.extend(toks)
        else:
            # Other continuation types — treat as new entry for non-para contexts
            # but still check for cnums in labels/etc.
            flush_para(base, marker, toks)
            current_folio  = None
            current_tokens = []

flush_para(current_folio, current_marker, current_tokens)

lines = []
def w(s=''):
    lines.append(str(s))

w("GREEK ORDINAL / ROUND-9 GLYPH INVESTIGATION")
w("=" * 70)
w()

# ── 1. Distribution of all c@NNN characters found ───────────────────────────
w("PART 1: ALL c@NNN OCCURRENCES BY CHARACTER VALUE")
w("-" * 70)

cnum_dist = Counter(occ['cnum'] for occ in occurrences)
w(f"  Total c@NNN occurrences: {len(occurrences)}")
w(f"  Unique character codes:  {len(cnum_dist)}")
w()
w(f"  {'c@NNN':>8}  {'count':>6}  {'sections'}")
w(f"  {'-----':>8}  {'-----':>6}  {'--------'}")
for cnum, cnt in sorted(cnum_dist.items(), key=lambda x: -x[1]):
    secs = Counter(occ['section'] for occ in occurrences if occ['cnum'] == cnum)
    sec_str = ', '.join(f"{s}:{c}" for s, c in secs.most_common())
    w(f"  {cnum:>8}  {cnt:>6}  {sec_str}")
w()

# ── 2. Focus on c@132 and c@133: bracket pair hypothesis ────────────────────
w("PART 2: c@132 AND c@133 — BRACKET PAIR ANALYSIS")
w("-" * 70)

occ_132 = [o for o in occurrences if o['cnum'] == 132]
occ_133 = [o for o in occurrences if o['cnum'] == 133]

w(f"  c@132 total: {len(occ_132)}")
w(f"  c@133 total: {len(occ_133)}")
w()

# Find co-occurrences: both 132 and 133 in same paragraph (folio + marker)
para_key = lambda o: (o['folio'], o.get('marker',''))
para_132 = defaultdict(list)
para_133 = defaultdict(list)
for o in occ_132:
    para_132[(o['folio'], o['section'])].append(o['para_pos'])
for o in occ_133:
    para_133[(o['folio'], o['section'])].append(o['para_pos'])

cooccur_folios = set(para_132.keys()) & set(para_133.keys())
w(f"  Folios where BOTH c@132 and c@133 appear: {len(cooccur_folios)}")
w()

w("  All c@132 occurrences:")
w(f"  {'folio':<10}  {'sec':<18}  {'pos':>5}  {'para_len':>8}  {'pos0?':>5}  context")
w(f"  {'-----':<10}  {'---':<18}  {'---':>5}  {'--------':>8}  {'-----':>5}  -------")
for o in sorted(occ_132, key=lambda x: (x['section'], x['folio'], x['para_pos'])):
    is_p0 = 'YES' if o['para_pos'] == 0 else 'no'
    w(f"  {o['folio']:<10}  {o['section']:<18}  {o['para_pos']:>5}  {o['para_len']:>8}  {is_p0:>5}  {o['context']}")
w()

w("  All c@133 occurrences:")
w(f"  {'folio':<10}  {'sec':<18}  {'pos':>5}  {'para_len':>8}  {'pos0?':>5}  context")
w(f"  {'-----':<10}  {'---':<18}  {'---':>5}  {'--------':>8}  {'-----':>5}  -------")
for o in sorted(occ_133, key=lambda x: (x['section'], x['folio'], x['para_pos'])):
    is_p0 = 'YES' if o['para_pos'] == 0 else 'no'
    w(f"  {o['folio']:<10}  {o['section']:<18}  {o['para_pos']:>5}  {o['para_len']:>8}  {is_p0:>5}  {o['context']}")
w()

# ── 3. Bracket content analysis ──────────────────────────────────────────────
w("PART 3: CONTENT BETWEEN c@132 AND c@133 IN SAME FOLIO")
w("-" * 70)
w("If they bracket an ordinal index, the content should be short and consistent.")
w()

# For each folio with both, find the span between closest 132 and 133
# Need the raw IVTFF to extract exact token sequences between them

# Re-parse to get per-folio full token sequences with CNUM markers
folio_para_toks = defaultdict(list)  # folio → full token sequence

current_folio  = None
current_tokens = []

def flush2(folio, tokens):
    if folio and tokens:
        base = re.sub(r'\.\d+$', '', folio)
        folio_para_toks[base].extend(tokens)

with open(IVTFF, encoding='utf-8', errors='replace') as fh:
    for line in fh:
        m = line_re.match(line.rstrip())
        if not m: continue
        fid, marker, text = m.group(1), m.group(2), m.group(3)
        base = re.sub(r'\.\d+$', '', fid)
        toks = tokenize_preserving_cnums(text)
        if '@P' in marker:
            flush2(current_folio, current_tokens)
            current_folio  = base
            current_tokens = toks[:]
        elif '+P' in marker and base == current_folio:
            current_tokens.extend(toks)

flush2(current_folio, current_tokens)

w(f"  {'folio':<10}  {'content_between_132_133':<40}  span_len  note")
w(f"  {'-----':<10}  {'----------------------':<40}  --------  ----")

bracket_spans = []
for folio, tokens in folio_para_toks.items():
    positions_132 = [i for i,(t,is_c,v) in enumerate(tokens) if is_c and v == 132]
    positions_133 = [i for i,(t,is_c,v) in enumerate(tokens) if is_c and v == 133]
    if not positions_132 or not positions_133: continue

    for p132 in positions_132:
        # Find closest c@133 AFTER this c@132
        after_133 = [p for p in positions_133 if p > p132]
        if not after_133: continue
        p133 = min(after_133)
        span = p133 - p132 - 1
        content_toks = [tokens[i][0] for i in range(p132+1, p133)]
        content_str  = ' '.join(content_toks)
        bracket_spans.append({
            'folio': folio,
            'p132': p132,
            'p133': p133,
            'span': span,
            'content': content_str,
            'section': folio_section.get(folio, '')
        })
        note = ''
        if p132 == 0: note = 'para-initial'
        elif span == 0: note = 'IMMEDIATE (no content)'
        w(f"  {folio:<10}  {content_str:<40}  {span:>8}  {note}")

w()
span_lengths = [b['span'] for b in bracket_spans]
if span_lengths:
    from statistics import mean, median, stdev
    w(f"  Span length stats: n={len(span_lengths)}, "
      f"mean={mean(span_lengths):.1f}, "
      f"median={median(span_lengths):.1f}, "
      f"min={min(span_lengths)}, max={max(span_lengths)}")
    content_lengths = Counter(b['span'] for b in bracket_spans)
    w(f"  Span length distribution: " + ", ".join(f"len={k}:{v}" for k,v in sorted(content_lengths.items())))
w()

# ── 4. Inter-occurrence spacing within pharma-recipes ────────────────────────
w("PART 4: INTER-OCCURRENCE SPACING WITHIN PHARMA-RECIPES")
w("-" * 70)
w("If c@132 marks ordinal entry positions (every N tokens), spacings should cluster.")
w()

# Get all c@132 positions within pharma-recipes, ordered by folio sequence
pharma_132 = [o for o in occ_132 if o['section'] == 'pharma_recipes']
pharma_133 = [o for o in occ_133 if o['section'] == 'pharma_recipes']

w(f"  pharma-recipes c@132 occurrences: {len(pharma_132)}")
w(f"  pharma-recipes c@133 occurrences: {len(pharma_133)}")
w()

# For the inline (non-position-0) occurrences, compute absolute token offset
# by accumulating token counts per folio

# Build cumulative token offsets for pharma folios in order
# Use folio order from IVTFF
pharma_folio_order = []
seen = set()
with open(IVTFF, encoding='utf-8', errors='replace') as fh:
    for line in fh:
        m = line_re.match(line.rstrip())
        if not m: continue
        fid = m.group(1)
        base = re.sub(r'\.\d+$', '', fid)
        if base not in seen and folio_section.get(base,'') == 'pharma_recipes':
            pharma_folio_order.append(base)
            seen.add(base)

# For pharma folios, track absolute token position of c@132/133
pharma_abs_132 = []  # list of (absolute_pos, folio, para_pos)
pharma_abs_133 = []

abs_offset = 0
current_folio  = None
current_tokens = []

def flush3(folio, tokens, abs_off):
    base = re.sub(r'\.\d+$', '', folio) if folio else None
    if not base or folio_section.get(base,'') != 'pharma_recipes':
        return abs_off
    for i, (tok, is_c, cnum) in enumerate(tokens):
        if is_c:
            if cnum == 132:
                pharma_abs_132.append((abs_off + i, base, i))
            elif cnum == 133:
                pharma_abs_133.append((abs_off + i, base, i))
    return abs_off + len(tokens)

abs_offset = 0
current_folio  = None
current_tokens = []

with open(IVTFF, encoding='utf-8', errors='replace') as fh:
    for line in fh:
        m = line_re.match(line.rstrip())
        if not m: continue
        fid, marker, text = m.group(1), m.group(2), m.group(3)
        base = re.sub(r'\.\d+$', '', fid)
        if folio_section.get(base,'') != 'pharma_recipes': continue

        toks = tokenize_preserving_cnums(text)

        if '@P' in marker:
            if current_folio:
                abs_offset = flush3(current_folio, current_tokens, abs_offset)
            current_folio  = base
            current_tokens = toks[:]
        elif '+P' in marker and base == current_folio:
            current_tokens.extend(toks)
        else:
            abs_offset = flush3(current_folio, current_tokens, abs_offset)
            current_folio  = None
            current_tokens = []
            # For labels/rings, count tokens but don't track cnums as paragraph content
            abs_offset += len(toks)

abs_offset = flush3(current_folio, current_tokens, abs_offset)

w(f"  Pharma absolute c@132 positions: {[x[0] for x in pharma_abs_132]}")
w(f"  Pharma absolute c@133 positions: {[x[0] for x in pharma_abs_133]}")
w()

if len(pharma_abs_132) >= 2:
    all_132_abs = sorted(x[0] for x in pharma_abs_132)
    spacings_132 = [all_132_abs[i+1] - all_132_abs[i] for i in range(len(all_132_abs)-1)]
    w(f"  c@132 spacings (consecutive occurrences): {spacings_132}")
    if spacings_132:
        w(f"  Mean spacing: {sum(spacings_132)/len(spacings_132):.1f} tokens")
        w(f"  Interpretation: if ordinal spacing, expect multiples of ~50-100 tokens")
w()

# ── 5. Paragraph-initial vs inline comparison ────────────────────────────────
w("PART 5: PARA-INITIAL vs INLINE OCCURRENCE PROFILES")
w("-" * 70)
w("Para-initial c@132 (pos=0): decorated initial (visual function)")
w("Inline c@132 (pos>0): candidate ordinal/semantic marker")
w()

for cnum_val, occ_list in [(132, occ_132), (133, occ_133)]:
    initial = [o for o in occ_list if o['para_pos'] == 0]
    inline  = [o for o in occ_list if o['para_pos'] > 0]
    w(f"  c@{cnum_val}:")
    w(f"    Para-initial (pos=0): {len(initial)}  → sections: " +
      str(Counter(o['section'] for o in initial)))
    w(f"    Inline (pos>0):       {len(inline)}  → sections: " +
      str(Counter(o['section'] for o in inline)))
    if inline:
        w(f"    Inline positions: {sorted(o['para_pos'] for o in inline)}")
        for o in sorted(inline, key=lambda x: (x['section'], x['folio'])):
            w(f"      {o['folio']:<10}  pos={o['para_pos']:>4}  sec={o['section']:<18}  {o['context']}")
    w()

# ── 6. Test: is c@132 inline spacing consistent with ordinal indexing? ───────
w("PART 6: ORDINAL INDEXING CONSISTENCY TEST")
w("-" * 70)
w("Hypothesis: c@132 marks the θ'=9th entry (or sequential entry) in a recipe series.")
w("If so, inline occurrences should fall at approximately the same")
w("fractional position within their respective paragraphs.")
w()

inline_132 = [o for o in occ_132 if o['para_pos'] > 0]
inline_133 = [o for o in occ_133 if o['para_pos'] > 0]

if inline_132:
    w("  Inline c@132: fractional position = para_pos / para_len")
    w(f"  {'folio':<10}  {'para_pos':>8}  {'para_len':>8}  {'frac_pos':>8}  section")
    fracs = []
    for o in sorted(inline_132, key=lambda x: x['para_pos'] / max(x['para_len'],1)):
        frac = o['para_pos'] / max(o['para_len'], 1)
        fracs.append(frac)
        w(f"  {o['folio']:<10}  {o['para_pos']:>8}  {o['para_len']:>8}  {frac:>8.3f}  {o['section']}")
    if fracs:
        mean_frac = sum(fracs)/len(fracs)
        w(f"  Mean fractional position: {mean_frac:.3f} (1.0 = terminal, 0.0 = initial)")
    w()

# ── 7. Check if pattern matches breviarium numbering ─────────────────────────
w("PART 7: BREVIARIUM NUMBERING HYPOTHESIS ASSESSMENT")
w("-" * 70)
w("Medieval pharmaceutical breviaria use ordinal indices (α', β'... θ')")
w("to number entries within a chapter or category.")
w()
w("Evidence FOR Greek ordinal indexing:")
w("  - c@132 (round-9 shape) clusters at para-initial positions → decorated initial")
w("  - Inline c@132 occurrences concentrated in pharma-recipes section")
w("  - c@132 and c@133 co-occur and appear to bracket a short span")
w("  - The bracket content is short (0-2 tokens) = consistent with an index symbol")
w()
w("Evidence AGAINST simple ordinal indexing:")
w("  - Only ~10 total occurrences — too rare for systematic entry numbering")
w("  - Occurrences are NOT evenly spaced through pharma section")
w("  - Content between 132 and 133 varies in length and form")
w()
w("Alternative interpretation:")
w("  - c@132 and c@133 together form a compound DEMARCATION MARK")
w("  - Functions as a special section heading or category boundary marker")
w("  - NOT repeated every N entries, but marks SPECIFIC structural boundaries")
w("  - The θ' connection may apply semantically (this IS the 9th category)")
w("    rather than syntactically (this IS the 9th token marker)")
w()

# ── 8. All c@NNN in context, full table ──────────────────────────────────────
w("PART 8: ALL c@NNN OCCURRENCES — FULL CONTEXT TABLE")
w("-" * 70)
w(f"  {'c@':>4}  {'folio':<10}  {'sec':<18}  {'pos':>4}  {'marker':<12}  context")
w(f"  {'--':>4}  {'-----':<10}  {'---':<18}  {'---':>4}  {'------':<12}  -------")
for o in sorted(occurrences, key=lambda x: (x['cnum'], x['section'], x['folio'])):
    w(f"  {o['cnum']:>4}  {o['folio']:<10}  {o['section']:<18}  {o['para_pos']:>4}  {str(o['marker'])[:12]:<12}  {o['context']}")
w()

with open(OUT, 'w') as fh:
    fh.write('\n'.join(lines))

print(f"Written: {OUT}")
print(f"Total c@NNN occurrences: {len(occurrences)}")
print(f"c@132: {len(occ_132)}, c@133: {len(occ_133)}")
