"""Build and revise a filterable directory at one temporary preview URL."""
from html import escape
from agent_tools import ask, workspace


def render(brief, previous=None):
    spec = ask("Design a tiny filterable directory for this request: " + brief +
               ". Return JSON with title (string) and items (array of 3 to 8 distinct strings). "
               "Use the prior spec for revisions: " + str(previous))
    items = spec["items"]
    if not isinstance(items, list) or not 3 <= len(items) <= 8:
        raise ValueError("Expected 3 to 8 directory entries")
    entries = "".join(f"<li>{escape(item)}</li>" for item in items)
    title = escape(spec["title"])
    page = f"""<!doctype html><meta charset=utf-8><title>{title}</title>
<h1>{title}</h1><label>Filter <input id=query type=search></label><ul>{entries}</ul>
<script>document.querySelector('#query').oninput = event => {{
  const q = event.target.value.toLowerCase();
  for (const row of document.querySelectorAll('li'))
    row.hidden = !row.textContent.toLowerCase().includes(q);
}};</script>"""
    return spec, page


if __name__ == "__main__":
    with workspace(encrypted_ports=[8000]) as box:
        brief = input("Directory to build: ")
        spec, page = render(brief)
        box.filesystem.make_directory("/work/site")
        box.filesystem.write_text(page, "/work/site/index.html")
        server = box.exec("python3", "-m", "http.server", "8000", "--bind", "0.0.0.0",
                          "--directory", "/work/site")
        url = box.tunnels()[8000].url
        print(url, flush=True)
        change = input("Open the URL, then describe one change: ")
        _, page = render(change, spec)
        box.filesystem.write_text(page, "/work/site/index.html")
        print("Refresh", url, flush=True)
        input("Press Enter to close the preview. ")
