"""Append authorized metre-unit revisions; never overwrite events or raw PCDs."""
from __future__ import annotations

import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest
from pallet.pose_review import PoseApplication
from pallet.pose_review_geometry import canonical
from pallet.pose_refinement import atomic_json,now
from pallet.structure_review import ReviewError


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--apply',action='store_true')
    parser.add_argument('--output',type=Path,default=PROJECT/'outputs/pallet_pose_review_validation_v12')
    args=parser.parse_args();out=args.output;out.mkdir(parents=True,exist_ok=True)
    if args.apply and not (out/'before_deployment.json').exists():raise ValueError('Create a read-only live DB backup before applying')
    result_path=out/('unit_migration.json' if args.apply else 'unit_migration_plan.json')
    if result_path.exists():raise ValueError('Do not overwrite previous unit migration evidence')
    dataset=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    app=PoseApplication(dataset,PROJECT/'outputs/pallet_pose_human_review_v1')
    if not app.units:raise ValueError('Missing dataset-bound authorized unit policy')
    snapshot=app.store.all();before=app.stats(snapshot);latest_before=app.store.latest(app.queue({'state':['all']})['keys'])
    records=[]
    for key in sorted(snapshot):
        current=app.store.get(key)
        if current['sensor']['scale_to_m'] is not None:continue
        item=dict(target_key=key,before_revision=current['revision'],before_sha256=hashlib.sha256(canonical(current)).hexdigest())
        if args.apply:
            converted=app.effective_review(current)
            converted.update(event_kind='unit_normalization',unit_policy=app.units.info(app.source(key)),
                unit_conversion_operator='system_appending_user_authorized_unit_revision',
                source_last_human_updated_at=current['updated_at'])
            try:
                saved=app.store.save(key,current['revision'],converted,allow_deleted=True)
                item.update(state='converted',after_revision=saved['revision'],scale_to_m=saved['sensor']['scale_to_m'],
                            length_multiplier=saved['unit_interpretation']['length_multiplier'])
            except ReviewError as exc:
                if exc.status!=409:raise
                item.update(state='concurrent_human_update_preserved')
        else:
            item.update(state='planned',scale_to_m=app.units.native_scale(app.source(key)))
        records.append(item)
        if len(records)%200==0:print(json.dumps(dict(processed=len(records),apply=args.apply)),flush=True)
    remaining=[k for k,v in app.store.all().items() if v['sensor']['scale_to_m'] is None]
    atomic_json(result_path,dict(state='passed' if not args.apply or not remaining else 'needs_followup',created_at=now(),
        apply=args.apply,authorization=app.units.config['authorization'],unit_policy=app.units.info(),
        before_stats=before,after_stats=app.stats(),records=records,counts=dict(Counter(v['state'] for v in records)),
        remaining_current_unknown_targets=remaining,latest_human_before=latest_before,latest_human_after=app.store.latest(app.queue({'state':['all']})['keys']),
        historical_events_rewritten=0,raw_PCD_files_modified=0,test_writes_to_live_database=0,
        authorized_unit_revisions_appended=sum(r['state']=='converted' for r in records)))
    print(json.dumps(dict(result=str(result_path),applied=args.apply,targets=len(records),remaining=len(remaining))),flush=True)


if __name__=='__main__':main()
