"""Only explicitly published report assets are reachable through the public app."""
import json
import threading
from urllib.error import HTTPError
from urllib.request import Request,urlopen

import pytest

from pallet.cluster_targets import digest
from pallet.mask_gallery import Gallery,GalleryServer


@pytest.fixture
def gallery(tmp_path):
    key='a'*24
    for folder,ext in [('cases','png'),('images','png'),('masks','png'),('labelme','json')]:
        (tmp_path/folder).mkdir();(tmp_path/folder/(key+'.'+ext)).write_bytes(b'fixture')
    for name,raw in [('report_zh.html',b'<script>window.fixture=1</script>'),('report-font.otf',b'font'),('FONT_LICENSE.txt',b'license')]:
        (tmp_path/name).write_bytes(raw)
    (tmp_path/'proposals.jsonl').write_text(json.dumps(dict(target_key=key))+'\n')
    (tmp_path/'verification.json').write_text(json.dumps(dict(state='passed',proposals_verified=1,proposals_sha256=digest(tmp_path/'proposals.jsonl'))))
    (tmp_path/'reviews_snapshot.sqlite3').write_bytes(b'secret historical payloads')
    (tmp_path/'access_key.txt').write_bytes(b'secret')
    server=GalleryServer(('127.0.0.1',0),Gallery(tmp_path));thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
    try:yield f'http://127.0.0.1:{server.server_port}',tmp_path
    finally:server.shutdown();server.server_close();thread.join()


def test_report_and_assets_only(gallery):
    base,_=gallery
    with urlopen(base+'/') as r:
        assert r.status==200 and b'window.fixture' in r.read()
        assert 'sha256-' in r.headers['Content-Security-Policy']
        assert r.headers['X-Content-Type-Options']=='nosniff'
    for path in ('/healthz','/cases/'+'a'*24+'.png','/labelme/'+'a'*24+'.json'):
        assert urlopen(base+path).status==200
    for path in ('/reviews_snapshot.sqlite3','/access_key.txt','/proposals.jsonl','/templates/','/cases/',
                 '/..%2Freviews_snapshot.sqlite3','/%2e%2e/access_key.txt','/api/annotations/example'):
        with pytest.raises(HTTPError) as error:urlopen(base+path)
        assert error.value.code==404


def test_methods_and_hash_checks(gallery):
    base,root=gallery
    for method in ('POST','PUT','PATCH','DELETE','OPTIONS','TRACE'):
        with pytest.raises(HTTPError) as error:urlopen(Request(base+'/',method=method))
        assert error.value.code==405
    with urlopen(Request(base+'/',method='HEAD')) as response:
        etag=response.headers['ETag'];assert not response.read()
    with pytest.raises(HTTPError) as error:urlopen(Request(base+'/',headers={'If-None-Match':etag}))
    assert error.value.code==304
    (root/'report_zh.html').write_text('unverified change')
    with pytest.raises(HTTPError) as error:urlopen(base+'/')
    assert error.value.code==503
