"""Exercise the exact article snippets against the public shieldlabs 1.0.0 package.

Uses signed fixtures and mocked reads, not fabricated live detection measurements.
"""
import hashlib
import hmac
import importlib.util
import json
import os
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import patch

from fastapi.testclient import TestClient
from shieldlabs import ShieldLabsError, webhooks

os.environ['SHIELDLABS_API_KEY'] = 'sec_11111111-22222222-33333333'
os.environ['SHIELDLABS_WEBHOOK_SECRET'] = 'whsec_11111111-22222222-33333333'
os.environ['SHIELDLABS_DOMAIN'] = 'example.com'
spec = importlib.util.spec_from_file_location('article_example', Path(__file__).with_name('app.py'))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
client = TestClient(module.app)
rid = '13f84f05-7c2a-4e9b-9f1d-2a6b8c0e4d11'
fixture = {
    'event_type': 'identification.scored', 'schema_version': '2026-06-01',
    'created_at': datetime.now(timezone.utc).isoformat(),
    'data': {'request_id': rid, 'domain': 'example.com', 'risk_score': 10,
             'observed_at': datetime.now(timezone.utc).isoformat(),
             'signals': [{'name': 'vpn', 'weight': 10}],
             'detection_flags': {'vpn': True}},
}
def sign(body):
    return 'sha256=' + hmac.new(os.environ['SHIELDLABS_WEBHOOK_SECRET'].encode(), body, hashlib.sha256).hexdigest()

raw = json.dumps(fixture).encode()
identification = webhooks.construct_event(raw, sign(raw), os.environ['SHIELDLABS_WEBHOOK_SECRET']).data
cases = [
    ('current', identification, 200),
    ('missing', None, 409),
    ('wrong_domain', replace(identification, domain='another.example'), 403),
    ('no_time', replace(identification, observed_at=None), 409),
    ('stale', replace(identification, observed_at=datetime.now(timezone.utc)-timedelta(minutes=6)), 409),
    ('future', replace(identification, observed_at=datetime.now(timezone.utc)+timedelta(minutes=6)), 409),
    ('rate_limited', replace(identification, risk_score=999), 409),
]
results=[]
for name, result, expected in cases:
    with patch.object(module.client.identifications, 'get', return_value=result):
        response=client.get('/identification/'+rid)
        assert response.status_code == expected, (name,response.status_code,response.text)
        if name=='current':
            assert response.json()['risk_score']==10 and response.json()['signals']==['vpn']
        results.append({'case':name,'status':response.status_code})
with patch.object(module.client.identifications, 'get', side_effect=ShieldLabsError('fixture error')):
    response=client.get('/identification/'+rid)
    assert response.status_code==503
    results.append({'case':'service_error','status':503})
assert client.get('/identification/not-a-uuid').status_code==422
results.append({'case':'invalid_uuid','status':422})
for name, body, header, expected in [
    ('valid_signature',raw,sign(raw),200),
    ('missing_signature',raw,'',400),
    ('tampered_body',raw+b' ',sign(raw),400),
    ('invalid_json',b'{',sign(b'{'),400),
]:
    response=client.post('/shieldlabs/webhook',content=body,headers={'X-Shield-Signature':header})
    assert response.status_code==expected,(name,response.status_code,response.text)
    results.append({'case':name,'status':response.status_code})
for name in ('webhook.ping','unknown.future'):
    body=json.dumps({'event_type':name,'schema_version':'2026-06-01'}).encode()
    assert client.post('/shieldlabs/webhook',content=body,headers={'X-Shield-Signature':sign(body)}).status_code==200
    results.append({'case':name,'status':200})
module.client.close()
report={'package':'shieldlabs 1.0.0 from PyPI','method':'Exact article snippets, signed fixture and mocked API reads','cases':results,'passed':len(results),'live_browser_to_python_e2e':False}
Path(__file__).with_name('python-verification.json').write_text(json.dumps(report,indent=2))
print(f'{len(results)} cases PASS on public shieldlabs 1.0.0; fixture test, not a live browser/API benchmark.')
