"""Local build boundary only. Never operates a browser or a live SHS service."""
from pathlib import Path
import hashlib
import json
import shutil
from fastapi.testclient import TestClient
from backend.app import create_app
from test_boundaries import client

DIST=Path(__file__).resolve().parents[1]/'frontend/dist'

def test_exact_install_assets_types_and_headers(tmp_path):
    c=TestClient(create_app(tmp_path/'data',DIST))
    policy=json.loads((DIST/'pwa-build.json').read_text())
    for asset in policy['assets']:
        r=c.get(asset['path'])
        assert r.status_code==200
        assert r.headers['content-type'].split(';')[0]==asset['type']
        assert hashlib.sha256(r.content).hexdigest()==asset['sha256']
        assert r.headers['cache-control']=='no-store'
    r=c.get('/service-worker.js')
    assert r.headers['cache-control']=='no-cache' and r.headers['service-worker-allowed']=='/'
    assert r.headers['x-content-type-options']=='nosniff'
    manifest=c.get('/manifest.webmanifest').json()
    assert manifest['id']==manifest['start_url']=='/workspace' and manifest['scope']=='/'
    assert {x['sizes'] for x in manifest['icons']}=={'192x192','512x512'}
    assert '?' not in json.dumps(manifest) and 'oak' not in json.dumps(manifest)

def test_no_fallback_html_for_missing_pwa_files_or_assets(tmp_path):
    empty=tmp_path/'dist';empty.mkdir();(empty/'index.html').write_text('<p>neutral app</p>')
    c=TestClient(create_app(tmp_path/'data',empty))
    for path in ['/service-worker.js','/manifest.webmanifest','/pwa-icon-v1-192.png','/offline-missing.html','/assets/missing.js']:
        assert c.get(path).status_code==404
    assert c.get('/workspace').status_code==200

def test_html_api_and_private_denials_remain_no_store(tmp_path):
    app=create_app(tmp_path/'data',DIST);anonymous=TestClient(app)
    for path in ['/workspace','/portal/oak-and-vale?code=synthetic','/preview/oak-and-vale','/api/session','/api/documents/private']:
        r=anonymous.get(path)
        assert r.headers['cache-control']=='no-store'
        assert 'Service-Worker-Allowed' not in r.headers
    owner=client(app)
    assert owner.get('/api/session').headers['cache-control']=='no-store'
    assert owner.get('/workspace').content==anonymous.get('/workspace').content

def test_fixed_qa_loopback_hostname_and_same_origin_write_boundary(tmp_path):
    app=create_app(tmp_path/'data',DIST)
    c=TestClient(app,base_url='http://note-review-v23.localhost:8796')
    assert c.get('/').status_code==200
    assert c.post('/api/logout',headers={'origin':'http://127.0.0.1:8794'}).status_code==403
    for host in ['pwa-qa.localhost.evil.example','note-review-v23.localhost.evil.example','untrusted.localhost','0.0.0.0','example.com']:
        assert c.get('/',headers={'host':host}).status_code==400
