#!/usr/bin/env python3
"""Reproduce the existing preparation-shell story without backend or devices."""
import json
import subprocess
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent
SESSION = subprocess.check_output(
    ["agent-browser", "session", "id", "--scope", "worktree", "--prefix", "guest-input-investigation"],
    text=True,
).strip()
URL = "http://localhost:6011/iframe.html?id=guest-preparationshell--tablet-landscape&viewMode=story"


def browser(*args, stdin=None):
    result = subprocess.run(
        ["agent-browser", "--session", SESSION, *args],
        input=stdin,
        text=True,
        capture_output=True,
        check=True,
    )
    return result.stdout.strip()


PROBE = r"""
(() => {
  const main = document.querySelector('main');
  const content = main?.firstElementChild?.lastElementChild;
  const fields = [...document.querySelectorAll('input')].map(input => {
    const rect = input.getBoundingClientRect();
    let box = {left: Math.max(0,rect.left), right: Math.min(innerWidth,rect.right), top: Math.max(0,rect.top), bottom: Math.min(innerHeight,rect.bottom)};
    for (let p = input.parentElement; p; p = p.parentElement) {
      const style = getComputedStyle(p);
      const parentRect = p.getBoundingClientRect();
      if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {
        box.top = Math.max(box.top,parentRect.top);
        box.bottom = Math.min(box.bottom,parentRect.top+p.clientHeight);
      }
      if (/(auto|scroll|hidden|clip)/.test(style.overflowX)) {
        box.left = Math.max(box.left,parentRect.left);
        box.right = Math.min(box.right,parentRect.left+p.clientWidth);
      }
    }
    const visibleWidth = Math.max(0,box.right-box.left);
    const visibleHeight = Math.max(0,box.bottom-box.top);
    const hit = visibleWidth > 0 && visibleHeight > 0 ? document.elementFromPoint((box.left+box.right)/2,(box.top+box.bottom)/2) : null;
    return {label: input.getAttribute('aria-label'),disabled:input.disabled,readOnly:input.readOnly,hasValue:input.value.length>0,rect:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},visibleWidth,visibleHeight,hittable:hit===input};
  });
  return {viewport:{width:innerWidth,height:innerHeight},mainHeight:main?.getBoundingClientRect().height,contentHeight:content?.getBoundingClientRect().height,contentClientHeight:content?.clientHeight,contentScrollHeight:content?.scrollHeight,documentScrollTop:document.scrollingElement.scrollTop,fields};
})()
"""

(ROOT / "screenshots").mkdir(exist_ok=True)

cases = []
run = {
    "started_at": datetime.now(timezone.utc).isoformat(),
    "target": URL,
    "environment": "Local Chromium, existing Storybook fixture; media disabled; no authentication or backend calls",
    "limitations": "Viewport height is simulated; this does not emulate an actual iPad software keyboard or establish the incident cause.",
    "cases": cases,
}


def record(case_id, title, width, height, expected, fill=False):
    browser("set", "viewport", str(width), str(height))
    if fill:
        browser("fill", 'input[aria-label="아이 이름"]', "입력확인")
        browser("fill", 'input[aria-label="전화번호 뒤 4자리"]', "0000")
    actual = json.loads(browser("eval", "--stdin", stdin=PROBE))
    ok = len(actual["fields"]) == 2 and all(
        not field["disabled"] and not field["readOnly"] and field["hittable"]
        for field in actual["fields"]
    )
    status = "PASS" if ok else "FAIL"
    screenshot = f"screenshots/{case_id}-{status.lower()}.png"
    browser("screenshot", str(ROOT / screenshot))
    case = {"id":case_id,"title":title,"status":status,"expected":expected,"actual":actual,"evidence":[screenshot]}
    if not ok:
        case["diagnosis"] = "Inputs remain enabled in the DOM, but the content scroll container collapses to zero height; the fields cannot be hit."
    cases.append(case)
    (ROOT / "results.json").write_text(json.dumps(run,ensure_ascii=False,indent=2)+"\n")
    print(json.dumps({"id":case_id,"status":status,"viewport":actual["viewport"],"contentHeight":actual["contentHeight"],"fields":actual["fields"]},ensure_ascii=False))


browser("set", "viewport", "1180", "680")
browser("open", URL)
browser("wait", 'input[aria-label="아이 이름"]')
record("TC1", "Usable form at ordinary tablet landscape height", 1180, 680, "Both fields are visible, enabled, and accept fixture text.", fill=True)
record("TC2", "Form remains reachable at a 210px viewport height", 1180, 210, "Both fields remain reachable directly or through the body scroll container.")
record("TC3", "Form recovers after restoring viewport height", 1180, 680, "Both fields become visible and accept text after height recovery.", fill=True)
browser("close")
