#!/usr/bin/env python3
"""Supersede 15 under-review Rule 350 rows rejected by the phonotactic linter."""

from __future__ import annotations
import datetime as dt, sqlite3
import bank_392
from process_ledger import ensure_schema, record_event

DB=bank_392.DB; LABEL=bank_392.LABEL; LOG=bank_392.PROCESS_LOG
NOW=dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00","Z")
OLD={
2:("I saw the jukujuku bronzewing dove here.","Ngayu jukujuku yaluy nyajin.","ngayu jukujuku yaluy nyajin | 1sg.NOM jukujuku.bronzewing-dove here see.PST"),
3:("I saw the dawadawa magpie here.","Ngayu dawadawa yaluy nyajin.","ngayu dawadawa yaluy nyajin | 1sg.NOM dawadawa.magpie here see.PST"),
4:("I saw the jurriyam satin bower bird here.","Ngayu jurriyam yaluy nyajin.","ngayu jurriyam yaluy nyajin | 1sg.NOM jurriyam.satin-bower-bird here see.PST"),
12:("You saw the jukujuku bronzewing dove there.","Yundu jukujuku yinyay nyajin.","yundu jukujuku yinyay nyajin | 2sg.NOM jukujuku.bronzewing-dove there see.PST"),
13:("You saw the dawadawa magpie there.","Yundu dawadawa yinyay nyajin.","yundu dawadawa yinyay nyajin | 2sg.NOM dawadawa.magpie there see.PST"),
14:("You saw the jurriyam satin bower bird there.","Yundu jurriyam yinyay nyajin.","yundu jurriyam yinyay nyajin | 2sg.NOM jurriyam.satin-bower-bird there see.PST"),
22:("He saw the jukujuku bronzewing dove here.","Nyulu jukujuku yaluy nyajin.","nyulu jukujuku yaluy nyajin | 3sg.NOM jukujuku.bronzewing-dove here see.PST"),
23:("He saw the dawadawa magpie here.","Nyulu dawadawa yaluy nyajin.","nyulu dawadawa yaluy nyajin | 3sg.NOM dawadawa.magpie here see.PST"),
24:("He saw the jurriyam satin bower bird here.","Nyulu jurriyam yaluy nyajin.","nyulu jurriyam yaluy nyajin | 3sg.NOM jurriyam.satin-bower-bird here see.PST"),
32:("The two of them saw the jukujuku bronzewing dove there.","Bula jukujuku yinyay nyajin.","bula jukujuku yinyay nyajin | 3du.NOM jukujuku.bronzewing-dove there see.PST"),
33:("The two of them saw the dawadawa magpie there.","Bula dawadawa yinyay nyajin.","bula dawadawa yinyay nyajin | 3du.NOM dawadawa.magpie there see.PST"),
34:("The two of them saw the jurriyam satin bower bird there.","Bula jurriyam yinyay nyajin.","bula jurriyam yinyay nyajin | 3du.NOM jurriyam.satin-bower-bird there see.PST"),
42:("They saw the jukujuku bronzewing dove here.","Jana jukujuku yaluy nyajin.","jana jukujuku yaluy nyajin | 3pl.NOM jukujuku.bronzewing-dove here see.PST"),
43:("They saw the dawadawa magpie here.","Jana dawadawa yaluy nyajin.","jana dawadawa yaluy nyajin | 3pl.NOM dawadawa.magpie here see.PST"),
44:("They saw the jurriyam satin bower bird here.","Jana jurriyam yaluy nyajin.","jana jurriyam yaluy nyajin | 3pl.NOM jurriyam.satin-bower-bird here see.PST"),
}

def main():
    issues=bank_392.scan_static()
    if issues: raise SystemExit("corrected source inventory fails: "+"; ".join(issues))
    records,hits=bank_392.source_audit()
    db=sqlite3.connect(DB);db.execute("PRAGMA foreign_keys=ON");db.execute("BEGIN");ensure_schema(db)
    bid=db.execute("SELECT id FROM batches WHERE label=?",(LABEL,)).fetchone()[0]
    for seq in sorted(OLD):
        sid,english,kuku,analysis,status=db.execute("SELECT id,english,kuku,analysis,status FROM sentences WHERE batch_id=? AND seq=?",(bid,seq)).fetchone()
        old_en,old_ku,old_an=OLD[seq]
        if (english,kuku,analysis,status)!=(old_en,old_ku,old_an,"under_review"): raise SystemExit(f"old row mismatch {seq}")
        new=bank_392.ROWS[seq-1]
        _,new_en,new_ku,new_an,frame,tier,words,loans,evidence,confidence=new
        collision=db.execute("SELECT b.label,s.seq FROM sentences s JOIN batches b ON b.id=s.batch_id WHERE lower(s.kuku)=lower(?) AND s.id!=? AND s.status!='rejected'",(new_ku,sid)).fetchall()
        if collision: raise SystemExit(f"replacement collision {seq}: {collision}")
        db.execute("INSERT INTO revisions(sentence_id,old_kuku,new_kuku,old_english,new_english,old_analysis,new_analysis,reason,created_at) VALUES(?,?,?,?,?,?,?,?,?)",(sid,old_ku,new_ku,old_en,new_en,old_an,new_an,"Rule 350 pre-close lint: source-dictionary form conflicts with established corpus phonotactic/reduplication gate; superseded by independently source-audited, zero-collision bird head.",NOW))
        db.execute("UPDATE sentences SET english=?,kuku=?,analysis=?,frame=?,tier=?,words_used=?,loans_used=?,evidence=?,confidence=?,updated_at=? WHERE id=?",(new_en,new_ku,new_an,frame,tier,words,loans,evidence,confidence,NOW,sid))
    record_event(db,batch_label=LABEL,phase="lint",event_type="preclose-lint-fail",actor="codex",detail="Initial whole-corpus lint found 15 issues: five each for unhyphenated lexical forms jukujuku/dawadawa and final-m jurriyam. Existing methodology excludes such forms rather than weakening the linter.",command="python3 lint_corpus.py",output_excerpt="19697 rows / 15 issues",artifact_path=LOG,created_at=NOW)
    record_event(db,batch_label=LABEL,phase="repair",event_type="replacement-source-audit",actor="codex",detail=f"Selected kurkunbay/kurrujuwa/mirrku after noun-card, zero-Patz-hit, zero-200-cell-collision and zero-lint audits; corrected counts={records}; hits={hits}.",artifact_path=LOG,created_at=NOW)
    record_event(db,batch_label=LABEL,phase="repair",event_type="revision-ledger-repair",actor="codex",detail="Inserted 15 revision rows and superseded the affected under-review sentence fields; no sentence or evidence row deleted.",command="python3 batch_scripts/repair_392.py",output_excerpt="15 revisions",artifact_path=LOG,created_at=NOW)
    db.commit();print("repaired batch-392: 15 revisions recorded; 50 rows remain under_review");return 0
if __name__=="__main__":raise SystemExit(main())
