"""Plan/apply append-only restoration of unchanged existing human confirmations."""
from contextlib import closing
import argparse
import hashlib
import json
from pathlib import Path
import sqlite3
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.mask_class_correction import ROOT,STATE
from pallet.mask_class_correction_review import ClassGallery,recoverable_confirmations,compute
from pallet.mask_model_training_data import read,jsonl,write,require
from pallet.mask_template_refined import readonly
from pallet.cluster_targets import digest


def recover(out,apply=False,expected_revision=None):
    out=Path(out).resolve();require(not out.exists(),'Preserve recovery evidence; choose a fresh output directory');out.mkdir(mode=0o700,parents=True)
    with closing(readonly(STATE/'mask_reviews.sqlite3')) as db:
        row=db.execute("SELECT revision,payload FROM reviews WHERE target_key='class_graph'").fetchone()
        raw_events=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' ORDER BY revision"))
    require(row and raw_events[-1]==row,'Latest current graph/history mismatch')
    history=[json.loads(raw) for _,raw in raw_events];state=json.loads(row[1])['state'];rs=jsonl(ROOT/'private/records.jsonl')
    proof=recoverable_confirmations(rs,history,state);groups,_=compute(rs,state)
    plan=dict(state='read_only_recovery_plan',expected_revision=row[0],manifest_sha256=digest(ROOT/'manifest.json'),recoverable_confirmations=proof,
        recovered_target_count=sum(groups[f]['targets'] for f in proof),current_confirmations=state['group_status'],
        old_raw_event_hashes=[hashlib.sha256(raw.encode()).hexdigest() for _,raw in raw_events],
        assignments_sha256=hashlib.sha256(json.dumps(state['assignments'],sort_keys=True).encode()).hexdigest(),no_new_semantic_confirmation=True)
    write(out/'plan.json',plan)
    if not apply:print(json.dumps(plan,ensure_ascii=False));return
    require(type(expected_revision)is int and row[0]==expected_revision,'Explicit expected revision required; graph changed')
    snapshot=out/'reviews_before_recovery.sqlite3'
    with closing(readonly(STATE/'mask_reviews.sqlite3')) as source:
        with closing(sqlite3.connect(snapshot)) as dest:source.backup(dest)
    snapshot.chmod(0o600)
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();gallery=ClassGallery(ROOT,STATE,key)
    value=gallery.editor.recover_confirmations(expected_revision)
    require(value['recovered_confirmations']==proof,'Recovery differs from approved revision plan')
    for field in ('assignments','anchor_choices','new_ids'):require(value['state'][field]==state[field],'Recovery changed graph structure/class mapping')
    with closing(readonly(STATE/'mask_reviews.sqlite3')) as db:after=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' ORDER BY revision"))
    require(after[:len(raw_events)]==raw_events,'Original events overwritten')
    receipt=dict(state='appended_existing_unchanged_human_confirmation_recovery',old_revision=expected_revision,recovery_revision=value['revision'],
        recovered_confirmations=proof,recovered_target_count=plan['recovered_target_count'],original_raw_history_preserved=True,
        assignments_anchors_new_ids_unchanged=True,no_new_semantic_confirmation=True,prior_review_snapshot_sha256=digest(snapshot),plan_sha256=digest(out/'plan.json'))
    write(out/'recovery.json',receipt);print(json.dumps(receipt,ensure_ascii=False))


if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path,required=True);p.add_argument('--apply',action='store_true');p.add_argument('--expected-revision',type=int);a=p.parse_args()
    recover(a.output,a.apply,a.expected_revision)
