"""Retained build_atlas.py research algorithms. Use analysis.py for portable CLI; see README and provenance."""
import json, os, re, sys, urllib.request, urllib.parse, time, html
from pathlib import Path
from PIL import Image, ImageOps, ImageDraw, ImageFont
BASE = Path('.')
FOLIOS = Path('folios')
PERLET = Path('per_letter')
TRANS = Path('transcription.ivtff')
LOCAL_F1R = Path('f1r.jpg')
TARGETS = ['f1r', 'f2r', 'f3r', 'f67r1', 'f68r1', 'f78r', 'f86v4', 'f100r', 'f116r']
WANTED_LABELS = ['1r', '2r', '3r', '67r', '68r', '78r', '86v', '100r', '116r']
EVA_UNITS = ['a', 'o', 'y', 'e', 'ee', 'i', 'ii', 'iin', 'n', 'm', 'ch', 'sh', 'd', 'l', 'r', 's', 'q', 'k', 't', 'p', 'f', 'cth', 'ckh', 'cph', 'cfh']
TOKENIZER = sorted(EVA_UNITS, key=len, reverse=True)
LINE_RE = re.compile('^<(f[0-9a-z]+)\\.(\\d+)[^>]*>\\s+(.*)$')

def clean_eva(text):
    text = re.sub('<[^>]*>', '', text)
    text = re.sub('\\[([^\\]:]+):[^\\]]*\\]', '\\1', text)
    text = re.sub('\\{[^}]*\\}', '', text)
    text = text.replace(',', ' ').replace('.', ' ')
    text = re.sub('[%!$@=+*?\\-]', '', text)
    text = re.sub('\\s+', ' ', text).strip()
    return text

def parse_transcription(folios):
    by_folio = {f: [] for f in folios}
    cur = None
    for raw in open(TRANS):
        line = raw.rstrip('\n')
        if line.startswith('#'):
            continue
        m = LINE_RE.match(line)
        if not m:
            continue
        folio, lineno, payload = (m.group(1), int(m.group(2)), m.group(3))
        payload = re.sub('<!.*?>', '', payload)
        eva = clean_eva(payload)
        if folio in by_folio and eva:
            by_folio[folio].append((lineno, eva))
    return by_folio

def detect_lines(img_path):
    im = Image.open(img_path).convert('L')
    W, H = im.size
    scale = 1.0
    if W > 1600:
        scale = 1600 / W
        im_s = im.resize((int(W * scale), int(H * scale)))
    else:
        im_s = im
    sw, sh = im_s.size
    px = im_s.load()
    rows = [0] * sh
    import numpy as np
    arr_full = np.asarray(im_s.convert('L'), dtype=np.int32)
    left, right = (int(sw * 0.1), int(sw * 0.9))
    band = arr_full[:, left:right]
    row_min = band.min(axis=1)
    row_med = np.median(band, axis=1)
    gmed = float(np.median(band))
    ink_thr = gmed * 0.65
    ink = (band < ink_thr).astype(np.int32)
    row_sum = ink.sum(axis=1)
    k = 3
    kern = np.ones(k) / k
    row_smooth = np.convolve(row_sum, kern, mode='same')
    abs_thr = max(6, int((right - left) * 0.02))
    in_line = row_smooth > abs_thr
    lines = []
    i = 0
    N = len(in_line)
    while i < N:
        if in_line[i]:
            j = i
            gap = 0
            while j < N:
                if in_line[j]:
                    gap = 0
                    j += 1
                else:
                    g0 = j
                    while j < N and (not in_line[j]):
                        j += 1
                    if j - g0 >= 3:
                        lines.append((i, g0))
                        break
            else:
                lines.append((i, j))
                break
            i = j
        else:
            i += 1
    merged = [(s, e) for s, e in lines if e - s >= 8]
    out = [(int(s / scale), int(e / scale)) for s, e in merged]
    return (out, (W, H))

def crop_line(img_path, y0, y1, pad=8):
    im = Image.open(img_path)
    W, H = im.size
    y0 = max(0, y0 - pad)
    y1 = min(H, y1 + pad)
    import numpy as np
    gray = im.convert('L').crop((0, y0, W, y1))
    arr = 255 - np.asarray(gray, dtype=np.int32)
    col_sum = (arr > 80).sum(axis=0)
    nz = np.where(col_sum > 2)[0]
    if len(nz) < 5:
        x0, x1 = (0, W)
    else:
        x0 = max(0, int(nz[0]) - 10)
        x1 = min(W, int(nz[-1]) + 10)
    return im.crop((x0, y0, x1, y1))

def tokenize_eva(word):
    out = []
    i = 0
    while i < len(word):
        matched = None
        for tok in TOKENIZER:
            if word.startswith(tok, i):
                matched = tok
                break
        if matched:
            out.append(matched)
            i += len(matched)
        else:
            i += 1
    return out
