"""Assistant drafts are editable, protected, and never fake human/pose saves."""
import copy
import json
import sqlite3

import pytest

from pallet.mask_preannotation import SCHEMA,FALSE_FLAGS,sha,validate_preannotation
from pallet.mask_gallery_review import ReviewError
from test_mask_gallery_review import editable,gallery_data,payload,KEY


@pytest.fixture
def assistant_draft(editable,tmp_path):
    editor=editable.editor;proposal=editor.proposals[KEY];proposal.pop('template')
    polygon=[[2,4],[22,5],[21,21],[3,20]]
    proposal.update(schema=SCHEMA,origin='assistant_visual_preannotation',polygon=polygon,vertex_count=4,
        status='assistant_preannotated_draft_pending_human_review',target_expected_revision=0,target_snapshot_payload_sha256=None,
        draft_source=dict(origin='assistant_visual_preannotation',target_key=KEY,snapshot_revision=0,current_payload_sha256=None),
        preannotation=dict(method='assistant_direct_native_image_contour_not_template_transfer',polygon_sha256=sha(polygon),
            image_sha256=editor.gallery.assets[f'/images/{KEY}.png'][2],crop_inspected=True,full_image_inspected=True,
            human_saved=False,note_zh='Synthetic actually drawn contour; not a human edit'),**dict.fromkeys(FALSE_FLAGS,False))
    path=tmp_path/'source_pose.sqlite3'
    with sqlite3.connect(path) as db:
        db.executescript('CREATE TABLE metadata(key TEXT,value TEXT);CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);CREATE TABLE events(target_key TEXT,revision INTEGER,payload TEXT);')
        db.execute('INSERT INTO metadata VALUES(?,?)',('binding',json.dumps(dict(formal_manifest_sha256=editor.formal_manifest_sha256))))
    editor.pose_database=path
    return editor,proposal,path


def test_drawn_draft_loaded_without_creating_human_or_pose_history(assistant_draft):
    editor,proposal,path=assistant_draft;before=path.read_bytes();detail=editor.detail(KEY)
    assert detail['assistant_preannotation_source'] and detail['proposal_polygon']==proposal['polygon']
    assert detail['review'] is None and detail['history']==[] and detail['template'] is None
    assert not detail['saved_pose_manual_source'] and not detail['saved_pose_review_source']
    assert editor.store.summary()=={} and path.read_bytes()==before


def test_only_explicit_human_save_creates_independent_review_without_pose_write(assistant_draft):
    editor,proposal,path=assistant_draft;before=path.read_bytes()
    saved=editor.save(KEY,payload(editor))
    assert saved['revision']==1 and saved['vertex_count']==4
    assert saved['polygon']==proposal['polygon'] and saved['human_edited']
    assert saved['preannotation_provenance']['assistant_draft_not_human_edit']
    assert all(saved[f] is False for f in ('human_mask_confirmed','human_pose_confirmed','automatic_training_eligible','robot_command_eligible','pose_store_written'))
    assert len(editor.store.history(KEY))==1 and path.read_bytes()==before


@pytest.mark.parametrize('field',FALSE_FLAGS)
def test_draft_rejects_false_human_template_or_coverage_claims(assistant_draft,field):
    editor,proposal,_=assistant_draft;proposal[field]=True
    with pytest.raises(ReviewError):editor.detail(KEY)
    assert not editor.store.summary()


def test_original_box_is_not_relabelled_as_an_assistant_preannotation(assistant_draft):
    _,proposal,_=assistant_draft;box=proposal['source']['bbox'];x,y,w,h=(box[k] for k in ('x','y','width','height'))
    proposal['polygon']=[[x,y],[x+w,y],[x+w,y+h],[x,y+h]];proposal['preannotation']['polygon_sha256']=sha(proposal['polygon'])
    with pytest.raises(ValueError,match='original rectangle'):validate_preannotation(proposal)


def test_first_new_pose_save_revokes_old_draft_without_overwriting_local_or_server_history(assistant_draft):
    editor,proposal,path=assistant_draft;data=payload(editor)
    with sqlite3.connect(path) as db:db.execute('INSERT INTO annotations VALUES(?,?,?)',(KEY,1,'{}'))
    with pytest.raises(ReviewError) as error:editor.save(KEY,data)
    assert error.value.status==409 and not editor.store.summary()


def test_saved_mask_survives_later_pose_source_change(assistant_draft):
    editor,proposal,path=assistant_draft;saved=editor.save(KEY,payload(editor))
    with sqlite3.connect(path) as db:db.execute('INSERT INTO annotations VALUES(?,?,?)',(KEY,1,'{}'))
    detail=editor.detail(KEY)
    assert detail['review']==saved and detail['proposal_dependency_stale']


@pytest.fixture
def task_gallery(tmp_path,gallery_data,monkeypatch):
    from pathlib import Path
    from PIL import Image
    from pallet.cluster_targets import digest
    from pallet.pose_review_geometry import canonical,raster_mask
    from pallet.mask_gallery import Gallery
    import pallet.mask_gallery as module
    parent,reviews=gallery_data;root=tmp_path/'outputs/prelabel_tasks';root.mkdir(parents=True)
    monkeypatch.setattr(module,'PROJECT',tmp_path)
    key='c'*24;source=dict(target_key=key,frame_id='synthetic/new-frame',split='train',box_index=0,
        bbox=dict(x=0.,y=0.,width=24.,height=24.),size=[48,24],source_pcd_sha256='c'*64)
    polygon=[[1,4],[22,3],[22,21],[2,20]]
    for folder in ('images','cases','masks','labelme'):(root/folder).mkdir()
    image=(parent/'images'/f'{KEY}.png').read_bytes()
    for folder in ('images','cases'):(root/folder/f'{key}.png').write_bytes(image)
    Image.fromarray(raster_mask(polygon,48,24).astype('uint8')*255).save(root/'masks'/f'{key}.png')
    (root/'labelme'/f'{key}.json').write_text(json.dumps(dict(shapes=[dict(points=polygon)])))
    proposal=dict(schema=SCHEMA,origin='assistant_visual_preannotation',target_key=key,class_id=4,source=source,
        polygon=polygon,vertex_count=4,formal_manifest_sha256='d'*64,mask_semantics='assistant_visible_face_draft',
        status='assistant_preannotated_draft_pending_human_review',target_expected_revision=0,target_snapshot_payload_sha256=None,
        draft_source=dict(origin='assistant_visual_preannotation',target_key=key,snapshot_revision=0,current_payload_sha256=None),
        preannotation=dict(method='assistant_direct_native_image_contour_not_template_transfer',polygon_sha256=sha(polygon),
            image_sha256=digest(root/'images'/f'{key}.png'),crop_inspected=True,full_image_inspected=True,human_saved=False,note_zh='synthetic drawn contour'),
        **dict.fromkeys(FALSE_FLAGS,False))
    (root/'proposals.jsonl').write_bytes(canonical(proposal)+b'\n')
    (root/'requests.jsonl').write_bytes(canonical(dict(target_key=key))+b'\n')
    (root/'report_zh.html').write_text('<html><article id="target-'+key+'"></article></html>')
    (root/'report-font.otf').write_bytes(b'font');(root/'FONT_LICENSE.txt').write_text('license')
    (root/'manifest.json').write_text('{}')
    public={str(p.relative_to(root)):digest(p) for p in root.rglob('*') if p.is_file() and p.name not in
        ('manifest.json','proposals.jsonl','requests.jsonl')}
    proof=dict(state='passed',request_count=1,requests_sha256=digest(root/'requests.jsonl'),proposals_sha256=digest(root/'proposals.jsonl'),
        preannotations_verified=True,formal_manifest_sha256='d'*64,parent_proposals_sha256=digest(parent/'proposals.jsonl'),public_assets=public)
    (root/'verification.json').write_bytes(canonical(proof))
    config=tmp_path/'task_config.json';config.write_bytes(canonical(dict(schema='preannotated_mask_worklist_v1',directory='outputs/prelabel_tasks',
        manifest_sha256=digest(root/'manifest.json'),verification_sha256=digest(root/'verification.json'))))
    gallery=Gallery(parent,reviews,'synthetic-prelabel-gallery-access-key-123456',config)
    path=tmp_path/'pose_source.sqlite3'
    with sqlite3.connect(path) as db:
        db.executescript('CREATE TABLE metadata(key TEXT,value TEXT);CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);CREATE TABLE events(target_key TEXT,revision INTEGER,payload TEXT);')
        db.execute('INSERT INTO metadata VALUES(?,?)',('binding',json.dumps(dict(formal_manifest_sha256='d'*64))))
    gallery.editor.pose_database=path
    return gallery,key,root,path


def test_preannotation_tasks_editable_but_do_not_inflate_counted_gallery(task_gallery):
    gallery,key,root,path=task_gallery
    assert gallery.count==2 and len(gallery.proposals)==2 and len(gallery.editor.proposals)==3
    assert gallery.manual_request_count==1 and key not in gallery.proposals
    assert gallery.editor.detail(key)['assistant_preannotation_source'] and gallery.editor.store.summary()=={}
    before=path.read_bytes();saved=gallery.editor.save(key,payload(gallery.editor,key))
    assert saved['revision']==1 and saved['preannotation_provenance']['worklist_manifest_sha256']
    assert gallery.count==2 and path.read_bytes()==before


def test_preannotation_worklist_has_authenticated_overlay_and_scoped_assets(task_gallery):
    from urllib.request import urlopen
    from urllib.error import HTTPError
    from test_mask_gallery_review import http,opener_login
    gallery,key,root,path=task_gallery
    # This fixture uses the standard synthetic access key expected by its login helper.
    from test_mask_gallery_review import PASSWORD
    import hmac,hashlib
    gallery.editor.access_key=PASSWORD
    gallery.editor.cookie_token=hmac.new(PASSWORD.encode(),b'gallery-mask-editor-v1',hashlib.sha256).hexdigest()
    with http(gallery) as base:
        page=urlopen(base+'/template-requests/').read()
        assert b'mgEditor' in page and b'target-'+key.encode() in page
        assert urlopen(base+'/template-requests/labelme/'+key+'.json').headers['Content-Type'].startswith('application/json')
        assert urlopen(base+'/images/'+key+'.png').read()==(root/'images'/f'{key}.png').read_bytes()
        with pytest.raises(HTTPError) as error:urlopen(base+'/api/review/targets/'+key)
        assert error.value.code==401
        opener=opener_login(base);detail=json.load(opener.open(base+'/api/review/targets/'+key))
        assert detail['assistant_preannotation_source'] and detail['review'] is None
        for route in ('/template-requests/proposals.jsonl','/template-requests/verification.json','/template-requests/internal/'):
            with pytest.raises(HTTPError) as error:urlopen(base+route)
            assert error.value.code==404
