import sys,json,urllib.request,hashlib
from pathlib import Path
sys.path[:0]=['/workspace/gewerk-integration','/workspace/gewerk-integration/tests']
from test_provider_http import ProviderHttp
from playwright.sync_api import sync_playwright,expect
O=Path(__file__).parent;f=ProviderHttp();f.setUp();outside=[];served=[]
try:
 _,b=f.server('portal')
 with sync_playwright() as p:
  browser=p.chromium.launch(executable_path='/usr/bin/chromium',headless=True,args=['--no-sandbox']);ctx=browser.new_context(viewport={'width':390,'height':950});page=ctx.new_page()
  def route(r):
   url=r.request.url
   if not url.startswith('https://gewerkflow.com/'):
    outside.append(url);r.abort();return
   assert r.request.method=='GET'
   with urllib.request.urlopen(b.url+url[len('https://gewerkflow.com'):]) as response:
    headers={k:v for k,v in response.headers.items() if k.lower() not in ('content-length','transfer-encoding','connection')};r.fulfill(status=response.status,headers=headers,body=response.read());served.append(url)
  ctx.route('**/*',route)
  page.goto('https://gewerkflow.com/musterablauf',wait_until='networkidle');expect(page.locator('.analytics-consent')).to_be_visible();assert page.evaluate('location.hostname')=='gewerkflow.com'
  assert not outside,outside;assert page.locator('script[data-gewerk-analytics]').count()==0
  page.locator('[data-analytics-choice=denied]').click();expect(page.locator('.analytics-consent')).to_be_hidden();page.reload(wait_until='networkidle');expect(page.locator('.analytics-consent')).to_be_hidden()
  assert page.evaluate('JSON.parse(localStorage.getItem("gewerk-analytics-consent-v1")).choice')=='denied'
  assert not outside,outside;assert not any(c['name'].startswith('_ga') for c in ctx.cookies());assert page.locator('script[data-gewerk-analytics]').count()==0
  browser.close()
 result=dict(hostname='gewerkflow.com',content_from_isolated_loopback_only=True,browser_executed_real_hostname_gated_script=True,initial_banner_visible=True,necessary_only_persisted_on_reload=True,external_requests_attempted=outside,google_tags_loaded=0,analytics_cookies_set=0,production_requests_sent=False,source_sha256={n:hashlib.sha256((Path('/workspace/gewerk-integration')/n).read_bytes()).hexdigest() for n in ('web/assets/public-analytics.js','gewerk/public_analytics.py')},isolated_gets=len(served))
 (O/'Consent-Browser.json').write_text(json.dumps(result,indent=2));print('Real hostname gate, no consent, necessary-only + reload, no external requests: OK')
finally:f.tearDown()
