#!/usr/bin/env python3
"""Prepare an interactive but write-blocked local preview of a public HTML snapshot."""

from __future__ import annotations

import argparse
from html import escape
from pathlib import Path


def preview_guard(source_url: str) -> str:
    base = escape(source_url.rstrip("/") + "/", quote=True)
    return f"""
<meta name="robots" content="noindex,nofollow">
<base href="{base}">
<style>
.preview-banner {{ position: sticky; top: 0; z-index: 99999; padding: 10px 16px;
  background: #7c2d12; color: #fff; text-align: center; font: 700 14px/1.4 sans-serif; }}
</style>
<script>
document.addEventListener('submit', function (event) {{
  event.preventDefault();
  event.stopImmediatePropagation();
  window.alert('Preview only: form submission is disabled.');
}}, true);
</script>
""".strip()


def prepare_snapshot(html: str, source_url: str) -> str:
    if "</head>" not in html.lower() or "<body" not in html.lower():
        raise ValueError("snapshot is not a complete HTML document")
    document = html.replace("</head>", preview_guard(source_url) + "\n</head>", 1)
    banner = '<div class="preview-banner">LIVE PAGE SNAPSHOT — READ ONLY — FORM SUBMISSION DISABLED</div>'
    body_start = document.lower().find("<body")
    body_end = document.find(">", body_start)
    return document[: body_end + 1] + "\n" + banner + document[body_end + 1 :]


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--source-url", required=True)
    args = parser.parse_args()
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(prepare_snapshot(args.input.read_text(encoding="utf-8"), args.source_url), encoding="utf-8")
    print(args.output.resolve())
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

