"""Replay the pinned AWS example's edit and refresh callbacks using local fixtures only."""
import argparse
import ast
import hashlib
import io
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
import zipfile


FRONT = "5f22e83e748e268c2933221c54e9aa1da9ac011bb03411faa8fd09a0a39344ca"
AGENT = "7a5216c98024525d6233ebdd59e065f8761a6983bf2a2c1ca958e75d7bfca3d9"


def archive(path, expected):
    data = path.read_bytes()
    if hashlib.sha256(data).hexdigest() != expected:
        raise ValueError(f"{path.name}: SHA-256 mismatch; get the linked version")
    return zipfile.ZipFile(io.BytesIO(data))


def extract_callbacks(front):
    index = front.read("index.html").decode()
    scripts = re.findall(r'<script[^>]+src="(/static/js/[^"]+)"', index)
    manifest = json.loads(front.read("asset-manifest.json"))
    if len(scripts) != 1 or scripts[0].lstrip("/") not in manifest["entrypoints"]:
        raise ValueError("entrypoint mismatch")
    active = scripts[0].lstrip("/")
    code = front.read(active).decode()
    source_map = json.loads(front.read(active + ".map"))
    sources = [name for name in source_map["sources"]
               if name.endswith(("/Home.tsx", "/agentCoreService.ts"))]
    if len(sources) != 2 or 'onClick:F,disabled:i,children:"Refresh"' not in code:
        raise ValueError("cannot identify original handlers")
    save_end = code.index(',variant:"contained",children:"Save Changes"')
    save_start = code.rindex("onClick:", 0, save_end) + len("onClick:")
    refresh_start = code.index(",F=async()=>{try{a(!0);") + len(",F=")
    refresh_end = code.index(";(0,o.useEffect)", refresh_start)
    list_start = code.index("async getIssues(){")
    list_end = code.index(",createIssue:", list_start)
    handlers = {"save": code[save_start:save_end], "refresh": code[refresh_start:refresh_end],
                "list": code[list_start:list_end]}
    return active, sources, handlers


# The three function bodies come from the verified active JS bundle. React setters,
# user input and the transport are controlled locally. No original application starts.
JS = """
const vm = require('node:vm');
const {readFileSync} = require('node:fs');
const {handlers, snapshots, payload, draftSeverity} = JSON.parse(readFileSync(0, 'utf8'));
const calls = [], errors = [];
let table = [], detail = null, draft = null, editing = false;
const env = vm.createContext({
  console: {error: (...args) => errors.push(args.map(String))},
  Qp: async request => {
    calls.push(JSON.parse(JSON.stringify(request)));
    if (snapshots === null) return {issues: []};
    if (JSON.stringify(request) !== JSON.stringify(payload)) throw Error('unexpected request');
    if (calls.length > snapshots.length) throw Error('unexpected additional request');
    return snapshots[calls.length - 1];
  },
  r: value => { table = value; }, c: value => { detail = value; },
  A: value => { editing = value; }, w: value => { draft = value; },
  a: () => {}, s: message => { if (message) errors.push(message); },
});
const evaluate = expression => vm.runInContext(expression, env, {timeout: 1000});
env.Zp = evaluate('({' + handlers.list + '})');
(async () => {
  if (snapshots === null) {
    await env.Zp.getIssues();
    return process.stdout.write(JSON.stringify(calls));
  }
  const save = evaluate('(' + handlers.save + ')');
  const refresh = evaluate('(' + handlers.refresh + ')');
  const levels = () => Object.fromEntries(table.map(row => [row.id, row.severity]));
  const runSave = async value => {
    env.n = table; env.E = value; draft = value; editing = Boolean(value);
    const count = calls.length;
    await save();
    return {transportCalls: calls.length - count, list: levels(), detail: detail?.severity,
            editorClosed: !editing, draftCleared: draft === null};
  };
  await refresh();
  const initial = levels();
  detail = table.find(row => row.id === 'DEMO-A');
  const noDraft = await runSave(null);
  const afterSave = await runSave({...detail, severity: draftSeverity});
  await refresh();
  const unchangedRefresh = levels(), openDetail = detail.severity;
  await refresh();
  if (errors.length || calls.length !== snapshots.length) throw Error(JSON.stringify(errors));
  process.stdout.write(JSON.stringify({initial, noDraft, afterSave, unchangedRefresh,
    detailStillOpenAfterRefresh: openDetail, alternateSnapshotRefresh: levels(), calls}));
})().catch(error => { console.error(error.message); process.exitCode = 1; });
"""


def browser_parts(node, handlers, snapshots=None, payload=None, draft=None):
    request = dict(handlers=handlers, snapshots=snapshots, payload=payload, draftSeverity=draft)
    process = subprocess.run([node, "-e", JS], input=json.dumps(request), text=True,
                             capture_output=True, timeout=8)
    if process.returncode:
        raise ValueError("callback replay failed: " + process.stderr.strip())
    return json.loads(process.stdout)


def project_rows(source, payload, rows):
    class Table:
        def __init__(self):
            self.scans = 0

        def scan(self):
            self.scans += 1
            return {"Items": rows}

    table = Table()
    tree = ast.parse(source)
    selected = [f for f in tree.body if isinstance(f, ast.FunctionDef)
                and f.name in {"invoke", "_list_issues"}]
    if {f.name for f in selected} != {"invoke", "_list_issues"}:
        raise ValueError("missing original GET functions")
    for function in selected:
        function.decorator_list = []  # Skip AgentCore registration.
    env = {"issues_table": table}
    exec(compile(ast.Module(body=selected, type_ignores=[]), "verified-agent.py", "exec"), env)
    response = env["invoke"](payload, None)
    if table.scans != 1:
        raise ValueError("GET did not perform exactly one fixture scan")
    return response, table.scans


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("frontend", type=Path)
    parser.add_argument("agent", type=Path)
    parser.add_argument("out", type=Path, help="new JSON record; existing files are preserved")
    parser.add_argument("--draft", choices=["Critical", "Low"], default="Critical")
    args = parser.parse_args()
    if args.out.exists():
        raise ValueError("choose a new output filename; existing record preserved")
    node = shutil.which("node")
    if not node:
        raise ValueError("Node.js required")
    with archive(args.frontend, FRONT) as front, archive(args.agent, AGENT) as agent:
        active, sources, handlers = extract_callbacks(front)
        source = agent.read("agriculture_repair_agent.py").decode()
    requests = browser_parts(node, handlers)
    if requests != [{"path": "/issues", "method": "GET"}]:
        raise ValueError("unexpected list request")
    snapshots, scans = [], []
    for severity in ["Medium", "Medium", "High"]:
        rows = [{"id": "DEMO-A", "severity": severity}, {"id": "DEMO-B", "severity": "Low"}]
        snapshot, scan = project_rows(source, requests[0], rows)
        snapshots.append(snapshot)
        scans.append(scan)
    record = browser_parts(node, handlers, snapshots, requests[0], args.draft)
    record.update(activeBundle=active, sourceMapSources=sources, draftInput=args.draft,
                  fixtureScans=scans, frontendSha256=FRONT, agentSha256=AGENT,
                  boundary="Offline compiled callbacks and GET route. React, transport and table are local fixtures.")
    with args.out.open("x", encoding="utf-8") as out:
        json.dump(record, out, ensure_ascii=False, indent=2)
        out.write("\n")
    for key in ("initial", "afterSave", "unchangedRefresh", "alternateSnapshotRefresh"):
        print(f"{key}: {record[key]}")


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, KeyError, subprocess.TimeoutExpired) as error:
        sys.exit(str(error))
