#!/usr/bin/env python3
"""Close Batch 397 after explicit five-lens review."""
from __future__ import annotations
import datetime as dt,json,sqlite3
from close_396 import TARGETS
from process_ledger import ensure_schema,record_event
DB="/mnt/donto-data/donto-resources/research/translation-training/kuku-yalanji-runpod-2026-06-30/synthetic/claude-synthetic-v1-2026-07-02/synthetic.db";LABEL="batch-397";NOW=dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00","Z");LOG="process_logs/batch-397-complementary-linter-clean-fish-set-f-singular-third-past-perception-after-rule354-process.md";LENSES=("morphology","lexicon","syntax","fidelity","register")
NOTES="COMPLEMENTARY LINTER-CLEAN FISH SET-F SINGULAR/THIRD PAST PERCEPTION AFTER RULE354 (Rule355). 50 accepted; exact complements; full 100-cell grid complete; source/sense boundaries retained; gap162->172."
LESSONS=[("source","Two-card fish inventories, zero-Patz profile and Patz support remained exact.","Rule355 source."),("process","All candidates were absent and opposites exactly Batch396.","Rule355 map."),("process","Rules354-355 complete the singular/third 100-cell grid.","Rule355 completion."),("process","Gap162->172 because the lower-gap inverse is duplicate.","Rule355 balance."),("process","Provisional kijukum/walarrji and other rejected heads remain excluded.","Rule355 rejects.")]+[("lexicon",f"{h} remains {g}; {n}.",f"Rule355 {h}.") for h,g,n in TARGETS]+[("morphology","Targets remain bare O.","Rule355 O."),("morphology","Mangkurr-mangkurr remains an indivisible head.","Rule355 whole."),("morphology","Pronouns remain bare A.","Rule355 A."),("morphology","Locals and nyajin remain fixed.","Rule355 support."),("syntax","Rows1-10 Ngayu...yinyay.","Rule355 b1."),("syntax","Rows11-20 Yundu...yaluy.","Rule355 b2."),("syntax","Rows21-30 Nyulu...yinyay.","Rule355 b3."),("syntax","Rows31-40 Bula...yaluy.","Rule355 b4."),("syntax","Rows41-50 Jana...yinyay.","Rule355 b5."),("fidelity","English preserves participant,label,location,past seeing only.","Rule355 fidelity."),("fidelity","No size/comparison/dialect/taboo/taxonomy/synonym/property/source/event content.","Rule355 exclude."),("register","Neutral elicitation register.","Rule355 register."),("process","AST proves 50 literal calls.","Rule355 authorship."),("process","Exact readback/lint/dup/integrity gate close.","Rule355 gates."),("process","Five lenses store 250 decisions.","Rule355 reviews."),("process","35 lessons/18 logs persist.","Rule355 storage."),("process","Export/books/live refresh.","Rule355 publish."),("process","Artifacts remain mounted.","Rule355 mounted."),("handoff","Rule356 opens the non-singular set-F matrix only after a fresh pronoun/cell audit.","Rule355 handoff."),("handoff","Do not reuse any completed Rule354-355 cell.","Rule355 no-reuse.")]
LEX=TARGETS+[("ngayu","first singular nominative","bare A"),("yundu","second singular nominative","bare A"),("nyulu","third singular nominative","bare A"),("bula","third dual nominative","bare A"),("jana","third plural nominative","bare A"),("yaluy","here","Yalanji local"),("yinyay","there","Yalanji local"),("nyajin","see; see.PST","past surface")]
def main():
 if len(LESSONS)!=35 or len(LEX)!=18:raise SystemExit(f"inventory {len(LESSONS)}/{len(LEX)}")
 db=sqlite3.connect(DB);db.execute("PRAGMA foreign_keys=ON");db.execute("BEGIN");ensure_schema(db);r=db.execute("SELECT id FROM batches WHERE label=?",(LABEL,)).fetchone()
 if not r:raise SystemExit("not banked")
 bid=r[0];c=db.execute("SELECT COUNT(*),COUNT(*) FILTER(WHERE status='under_review') FROM sentences WHERE batch_id=?",(bid,)).fetchone();total=db.execute("SELECT COUNT(*) FROM sentences WHERE status IN('accepted','revised','under_review')").fetchone()[0];before,wb=db.execute("SELECT COUNT(*),SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1) FROM sentences WHERE status IN('accepted','revised')").fetchone()
 if c!=(50,50) or (total,before,wb)!=(19947,19897,134947):raise SystemExit(f"pre {c}/{total}/{before}/{wb}")
 ids=[x[0] for x in db.execute("SELECT id FROM sentences WHERE batch_id=? ORDER BY seq",(bid,))];db.executemany("INSERT INTO reviews(sentence_id,round,lens,verdict,issues,suggested_fix,reviewer,created_at) VALUES(?,?,?,?,?,?,?,?)",[(sid,1,l,"pass",None,None,"codex-main-five-lens",NOW) for sid in ids for l in LENSES]);db.executemany("INSERT INTO lessons(batch_id,category,lesson,guide_change,created_at) VALUES(?,?,?,?,?)",[(bid,c,l,g,NOW) for c,l,g in LESSONS])
 for h,g,n in LEX:
  p="pronoun" if h in {"ngayu","yundu","nyulu","bula","jana"} else "demonstrative" if h in {"yaluy","yinyay"} else "verb-tr" if h=="nyajin" else "noun";conj="l" if h=="nyajin" else None;s=json.dumps([{"sense":g,"definition":n,"status":"attested"}],ensure_ascii=False);a=json.dumps([{"source":LABEL,"ref":"five-lens close","quote":n}],ensure_ascii=False);note=f"batch-397: {n}"
  db.execute("""INSERT INTO lexemes(headword,phonemic,pos,conj_class,case_class,gloss,senses,attestation,allomorphy,morphology,collocations,usage_notes,antonyms_contrasts,corpus_freq,status,verified_at,notes) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(headword) DO UPDATE SET verified_at=excluded.verified_at,status=excluded.status,notes=CASE WHEN lexemes.notes IS NULL OR lexemes.notes='' THEN excluded.notes WHEN instr(lexemes.notes,?)>0 THEN lexemes.notes ELSE lexemes.notes||'; '||excluded.notes END""",(h,None,p,conj,"NA",g,s,a,None,None,None,n,None,0,"verified",NOW,note,LABEL));db.execute("INSERT INTO lexeme_log(headword,action,detail,created_at) VALUES(?,?,?,?)",(h,"batch-397-verify",n,NOW))
 for ph,et,d in [("lint","under-review-lint-green",f"Lint {total}/0; verified {before}."),("review","five-lens-pass","250/250 passed; exact complements and fish boundaries retained."),("review","review-detail","No size/comparison/dialect/taboo/taxonomy/synonym/property/source/event drift."),("review","lesson-inventory","35 lessons."),("review","lexeme-source-log","18 logs.")]:record_event(db,batch_label=LABEL,phase=ph,event_type=et,actor="codex",detail=d,artifact_path=LOG,created_at=NOW)
 db.execute("UPDATE sentences SET status='accepted',updated_at=? WHERE batch_id=?",(NOW,bid));db.execute("UPDATE batches SET notes=?,cheatsheet_version=?,guide_version=? WHERE id=?",(NOTES,"Rule355 accepted","operator-guide-2026-07-10",bid));after,wa=db.execute("SELECT COUNT(*),SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1) FROM sentences WHERE status IN('accepted','revised')").fetchone();rv=db.execute("SELECT COUNT(*) FROM reviews WHERE sentence_id IN(SELECT id FROM sentences WHERE batch_id=?)",(bid,)).fetchone()[0]
 if (after,wa,rv)!=(19947,135147,250):raise SystemExit(f"post {after}/{wa}/{rv}")
 record_event(db,batch_label=LABEL,phase="close",event_type="close-success",actor="codex",detail=f"accepted=50 reviews=250 lessons=35 logs=18 verified {before}->{after} words {wb}->{wa}.",command="python3 batch_scripts/close_397.py",artifact_path=LOG,created_at=NOW);db.commit();print(f"closed batch-397: {before}->{after}");return 0
if __name__=="__main__":raise SystemExit(main())
