"""Success check shared by both conditions.

A run directory passes when, for every memo in memos/, transcripts/<same stem>.txt exists, is non-empty,
contains at least 10 CJK characters, and is plausibly the right recording (character-level similarity to the
reference script in corpus/memos.json >= 0.5). Usage: python check.py <run_dir>
"""
import difflib
import json
import pathlib
import re
import sys

HERE = pathlib.Path(__file__).resolve().parent
REF = {m['id']: m['text'] for m in json.loads((HERE.parent / 'corpus' / 'memos.json').read_text())['memos']}
CJK = re.compile(r'[一-鿿]')


def norm(s):
    return re.sub(r'[\s，。、！？,.!?：:；;“”"\'（）()]', '', s).lower()


def check(run_dir):
    run_dir = pathlib.Path(run_dir)
    memos = sorted((run_dir / 'memos').glob('*.wav'))
    files = {}
    for m in memos:
        t = run_dir / 'transcripts' / f'{m.stem}.txt'
        row = {'exists': t.exists()}
        if t.exists():
            text = t.read_text(encoding='utf-8', errors='replace')
            row.update(chars=len(text.strip()), cjk=len(CJK.findall(text)),
                       similarity=round(difflib.SequenceMatcher(None, norm(text), norm(REF.get(m.stem, ''))).ratio(), 3),
                       head=text.strip()[:40])
            row['ok'] = row['chars'] > 0 and row['cjk'] >= 10 and row['similarity'] >= 0.5
        else:
            row['ok'] = False
        files[m.stem] = row
    others = sorted(str(p.relative_to(run_dir)) for p in (run_dir / 'transcripts').rglob('*')) if (run_dir / 'transcripts').exists() else []
    return {'success': bool(files) and all(r['ok'] for r in files.values()),
            'n_ok': sum(r['ok'] for r in files.values()), 'n_memos': len(files),
            'files': files, 'transcripts_dir_listing': others}


if __name__ == '__main__':
    print(json.dumps(check(sys.argv[1]), ensure_ascii=False, indent=1))
