# -*- coding: utf-8 -*-
"""
Recited-consonant audit, part 2: how reader-dependent is each holding case?

Corpus Coranicum marks a reading that departs from the written consonant with a
parenthesis: s(ṣ)irāṭ = "recited sīn where ṣād is written". This script collects
every such notation in the thirteen counted sūrahs, classifies it, and recomputes
every case under each reader who departs from the page.
"""
import sys, io, contextlib, importlib.util, re
from collections import defaultdict

buf = io.StringIO()
with contextlib.redirect_stdout(buf):
    spec = importlib.util.spec_from_file_location('c19', '/tmp/read/count19.py')
    m = importlib.util.module_from_spec(spec); sys.argv = ['count19.py']
    try: spec.loader.exec_module(m)
    except SystemExit: pass

CC = '/tmp/cc/data'
v = open(f'{CC}/quran_variants/allvariants.xml', encoding='utf8').read()
items = re.findall(r'<item xml:id="(variant_\d+)">(.*?)</item>', v, re.S)
REL = {7, 19, 36, 38, 40, 41, 42, 43, 44, 45, 46, 50, 68}

# reader -> sura -> list of (ref, written letter, recited letter)
dep = defaultdict(lambda: defaultdict(list))
for vid, b in items:
    names = re.findall(r'<persName key="variantreader_\d*">([^<]*)</persName>', b)
    for ref, form in re.findall(r'<w n="(\d{3}:\d{3}:\d{3})">\s*([^\s<]+)', b):
        su = int(ref[:3])
        if su not in REL: continue
        for rec, wri in re.findall(r'(\w)\((\w)\)', form):
            for nm in names:
                dep[nm][su].append((ref, wri, rec))

print('=== every written/recited departure Corpus Coranicum records in the thirteen sūrahs ===')
for nm in sorted(dep):
    tot = sum(len(x) for x in dep[nm].values())
    kinds = sorted({(w, r) for su in dep[nm] for _, w, r in dep[nm][su]})
    print(f'  {nm:<12} {tot:>3} words   written→recited: {", ".join(f"{w}→{r}" for w, r in kinds)}')
    for su in sorted(dep[nm]):
        refs = sorted({ref for ref, w, r in dep[nm][su]})
        print(f'      sura {su:>2}: {len(refs)} — {", ".join(refs)}')

# --- what each departure does to the counts
# sirat: written ṣād, recited sīn (Qunbul). Halaf's z(ṣ) is išmām — the same letter, coloured; no change.
# qila: written qāf+wāw+yāʾ, recited with vowel išmām — vowel only; no change.
SIRAT = defaultdict(int)
for su in dep.get('Qunbul', {}):
    for ref, w, r in dep['Qunbul'][su]:
        if (w, r) == ('ṣ', 's'): SIRAT[su] += 1
SIRAT = {su: len({ref for ref, w, r in dep['Qunbul'][su] if (w, r) == ('ṣ', 's')}) for su in dep.get('Qunbul', {})}
print('\nṣād-written / sīn-recited words per sūrah (Qunbul):', SIRAT)

B = m.BASMALA
def T(sus): return ''.join(B + m.SURA[s] for s in sus)
CASES = [('Qāf-50', [50], ['q'], 57), ('Qāf-42', [42], ['q'], 57),
         ('ʿAyn-Sīn-Qāf-42', [42], ['ayn','sin','q'], 209),
         ('Ḥā-Mīm cluster', [40,41,42,43,44,45,46], ['ha','m'], 2147),
         ('Yā-Sīn', [36], ['ya','sin'], 285),
         ('K-H-Y-ʿA-Ṣ', [19], ['k','h','ya','ayn','sad'], 798),
         ('Ṣād cluster', [7,19,38], ['sad'], 153),
         ('Nūn-68', [68], ['n'], 132)]
print(f"\n{'case':<17}{'page (rasm)':>12}{'Ḥafṣ':>8}{'Qunbul':>9}   note")
for name, sus, letters, published in CASES:
    page = sum(m.count(T(sus), L, 'T8') for L in letters)
    hafs = page + (-1 if name == 'Ṣād cluster' else 0)          # Ḥafṣ recites basṭatan (sīn) at 7:69
    q = page
    for su in sus:
        n = SIRAT.get(su, 0)
        if 'sad' in letters: q -= n           # ṣād recited as sīn
        if 'sin' in letters: q += n           # ...and heard as sīn
    if name == 'Ṣād cluster': q -= 1           # Qunbul also has the 7:69 sīn
    f = lambda x: f'{x}{" ✓" if x % 19 == 0 else "  "}'
    print(f'{name:<17}{f(page):>12}{f(hafs):>8}{f(q):>9}   published {published}')
