"""Manual request files cannot turn the gallery into a database/file browser."""
import json
from pathlib import Path
import pytest

from pallet.cluster_targets import digest
from pallet.mask_template_requests import load_requests
from pallet.pose_review_geometry import canonical
from test_mask_gallery_review import gallery_data,http
from urllib.request import urlopen
from urllib.error import HTTPError


@pytest.fixture
def request_config(tmp_path):
    root=tmp_path/'outputs/requests';root.mkdir(parents=True);key='a'*24
    files=['report_zh.html','report-font.otf','FONT_LICENSE.txt',f'cases/{key}.png',f'images/{key}.png']
    for name in files:
        p=root/name;p.parent.mkdir(exist_ok=True);p.write_bytes(b'<html>requests</html>' if name.endswith('.html') else b'fixture')
    (root/'requests.jsonl').write_bytes(canonical(dict(target_key=key))+b'\n')
    (root/'manifest.json').write_text('{}')
    verified=dict(state='passed',request_count=1,requests_sha256=digest(root/'requests.jsonl'),public_assets={n:digest(root/n) for n in files})
    config=tmp_path/'config.json'
    def publish():
        (root/'verification.json').write_bytes(canonical(verified))
        config.write_bytes(canonical(dict(directory='outputs/requests',manifest_sha256=digest(root/'manifest.json'),verification_sha256=digest(root/'verification.json'))))
    publish();return tmp_path,root,config,verified,publish


def test_exact_allowlist_and_separate_manual_count(request_config):
    project,root,config,verified,_=request_config
    value=load_requests(config,project)
    assert value['count']==1 and len(value['assets'])==6
    assert value['assets']['/template-requests/']==value['assets']['/template-requests/report_zh.html']
    assert all(k.startswith('/template-requests/') for k in value['assets'])
    assert '/template-requests/requests.jsonl' not in value['assets']


@pytest.mark.parametrize('attack',['private_database','traversal','missing_image','asset_edit','duplicate_target','count'])
def test_reject_unverified_or_private_request_assets(request_config,attack):
    project,root,config,verified,publish=request_config
    if attack in ('private_database','traversal'):
        verified['public_assets']['reviews.sqlite3' if attack=='private_database' else '../secret.txt']='f'*64
    elif attack=='missing_image':verified['public_assets'].pop('images/'+'a'*24+'.png')
    elif attack=='asset_edit':(root/'report_zh.html').write_text('changed')
    elif attack=='duplicate_target':
        p=root/'requests.jsonl';p.write_bytes(p.read_bytes()*2);verified['requests_sha256']=digest(p)
    else:verified['request_count']=2
    publish()
    with pytest.raises(ValueError):load_requests(config,project)


def test_requests_do_not_change_accepted_gallery_inventory(request_config,gallery_data,monkeypatch):
    import pallet.mask_gallery as module
    project,root,config,verified,_=request_config
    parent,_=gallery_data;monkeypatch.setattr(module,'PROJECT',project)
    gallery=module.Gallery(parent,requests_config=config)
    assert gallery.count==2 and gallery.manual_request_count==1 and len(gallery.proposals)==2
    with http(gallery) as base:
        health=json.load(urlopen(base+'/healthz'))
        assert health['targets']==2 and health['manual_template_requests']==1
        assert urlopen(base+'/template-requests/').read()==(root/'report_zh.html').read_bytes()
        assert b'id="manualTemplateRequests"' in urlopen(base+'/').read()
        for private in ('requests.jsonl','manifest.json','verification.json','reviews.sqlite3'):
            with pytest.raises(HTTPError) as error:urlopen(base+'/template-requests/'+private)
            assert error.value.code==404


def test_pending_worklist_needs_independent_seal_before_status_can_be_shown_as_verified(request_config):
    project,root,config,verified,publish=request_config
    page=root/'report_zh.html';page.write_text('<html>待独立验收，尚未激活 · 待独立验收</html>')
    verified['public_assets']['report_zh.html']=digest(page);publish()
    with pytest.raises(ValueError,match='independent seal'):load_requests(config,project)
    proof=dict(verified,manifest_sha256=digest(root/'manifest.json'))
    (root/'independent_verification.json').write_bytes(canonical(proof))
    value=load_requests(config,project)
    assert value['online_page_normalized'] and '已独立核验' in value['page'] and '尚未激活' not in value['page']
    assert '尚未激活' in page.read_text()
    proof['manifest_sha256']='0'*64;(root/'independent_verification.json').write_bytes(canonical(proof))
    with pytest.raises(ValueError,match='publication binding'):load_requests(config,project)


def test_normalized_task_aliases_preserve_sealed_html_and_fail_closed_on_asset_edit(request_config,gallery_data,monkeypatch):
    import pallet.mask_gallery as module
    project,root,config,verified,publish=request_config;parent,_=gallery_data
    monkeypatch.setattr(module,'PROJECT',project)
    page=root/'report_zh.html';page.write_text('<html>待独立验收，尚未激活</html>')
    verified['public_assets']['report_zh.html']=digest(page);publish()
    (root/'independent_verification.json').write_bytes(canonical(dict(verified,manifest_sha256=digest(root/'manifest.json'))))
    original=page.read_bytes();gallery=module.Gallery(parent,requests_config=config)
    with http(gallery) as base:
        for route in ('/template-requests/','/template-requests/report_zh.html'):
            with urlopen(base+route) as response:
                assert '已独立核验'.encode() in response.read();assert response.headers['ETag']
        assert page.read_bytes()==original
        page.write_bytes(original+b'changed')
        with pytest.raises(HTTPError) as error:urlopen(base+'/template-requests/')
        assert error.value.code==503
