"""Check the chapter fixture over loopback without starting Docker services."""

import csv
import hashlib
import io
import json
import selectors
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from html import unescape
from pathlib import Path
import re


ROOT = Path(__file__).resolve().parents[2]
SOURCE = Path(__file__).with_name("serve.py")
WRAPPER = r'''
import http.server
import json
import runpy
import sys

original_server = http.server.HTTPServer
def loopback_server(address, handler):
    if address != ("0.0.0.0", 8090):
        raise RuntimeError("Fixture listener changed; review test isolation")
    server = original_server(("127.0.0.1", 0), handler)
    print(json.dumps({"host": "127.0.0.1", "port": server.server_port}), flush=True)
    return server

http.server.HTTPServer = loopback_server
runpy.run_path(sys.argv[1], run_name="__main__")
'''


def main():
    article = (ROOT / "content/16-ingestion-workbench.html").read_text(encoding="utf-8")
    section = re.search(r'<section id="ingestion-fixture">([\s\S]*?)</section>', article)
    if section is None:
        raise AssertionError("Chapter fixture section not found")
    blocks = [unescape(block) for block in re.findall(
        r"<pre><code>([\s\S]*?)</code></pre>", section.group(1))]
    expected_code = next(block for block in blocks if block.startswith("import json\n"))
    code = SOURCE.read_text(encoding="utf-8")
    assert code == expected_code + "\n", "serve.py differs from chapter code"
    print("UTC:", datetime.now(timezone.utc).isoformat(), flush=True)
    print("Python:", sys.version.split()[0], flush=True)
    print("serve.py SHA256:", hashlib.sha256(code.encode()).hexdigest(), flush=True)
    print("PASS: serve.py exactly matches the HTML-decoded chapter block (+ final newline).", flush=True)
    # Disable environment proxy handling: every request stays on loopback.
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    checks = 0
    with tempfile.TemporaryDirectory(prefix="sectools-fixture-check-") as directory:
        copy = Path(directory) / "serve.py"
        copy.write_text(code, encoding="utf-8")
        process = subprocess.Popen(
            [sys.executable, "-u", "-c", WRAPPER, str(copy)],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        try:
            with selectors.DefaultSelector() as selector:
                selector.register(process.stdout, selectors.EVENT_READ)
                if not selector.select(timeout=10):
                    raise TimeoutError("Fixture did not start within 10 seconds")
                line = process.stdout.readline()
            if not line:
                raise RuntimeError("Fixture exited before announcing its listener: " + process.stderr.read().strip())
            listener = json.loads(line)
            assert listener["host"] == "127.0.0.1"
            base = "http://127.0.0.1:" + str(listener["port"])
            print("Listener:", base, "(temporary; random available port)", flush=True)

            def get(path, mime=None, status=200):
                nonlocal checks
                try:
                    response = opener.open(base + path, timeout=5)
                except urllib.error.HTTPError as error:
                    response = error
                with response:
                    body = response.read()
                    assert response.status == status, (path, response.status, status)
                    assert int(response.headers["Content-Length"]) == len(body), path
                    if mime:
                        assert response.headers.get_content_type() == mime, path
                        assert response.headers.get_content_charset() == "utf-8", path
                checks += 1
                return body

            rows = list(csv.DictReader(io.StringIO(get("/sample.csv", "text/csv").decode())))
            assert rows == [
                {"domain": "login.example", "source_note": "SecTools Lab teaching data"},
                {"domain": "mail.example", "source_note": "SecTools Lab teaching data"}]
            print("PASS: CSV header, two rows, source notes, MIME and byte length.", flush=True)

            items = [
                {"id": "lab-domain-1", "domain": "login.example"},
                {"id": "lab-domain-2", "domain": "mail.example"}]
            assert json.loads(get("/sample.json", "application/json")) == {"items": items}
            print("PASS: JSON items, stable source IDs and domain values.", flush=True)

            rss = ET.fromstring(get("/sample.xml", "application/rss+xml"))
            assert rss.tag == "rss" and rss.attrib["version"] == "2.0"
            entries = rss.findall("./channel/item")
            assert len(entries) == 1
            entry = entries[0]
            assert entry.findtext("title") == "SecTools Lab RSS exercise"
            assert entry.findtext("guid") == "sectools-lab-rss-001"
            assert entry.findtext("link") == "http://fixture:8090/article.html"
            assert "teaching value" in entry.findtext("description")
            from email.utils import parsedate_to_datetime
            published = parsedate_to_datetime(entry.findtext("pubDate"))
            assert abs((datetime.now(timezone.utc) - published).total_seconds()) < 60
            print("PASS: RSS 2.0, one item, GUID/link/description and fresh UTC pubDate.", flush=True)
            assert b"Domain role unknown" in get("/article.html", "text/html")
            print("PASS: local article response (RSS Docker hostname not dereferenced).", flush=True)

            for query, expected in [("", items[:1]), ("?offset=0", items[:1]),
                                    ("?offset=1", items[1:]), ("?offset=2", []),
                                    ("?offset=99", []), ("?offset=-1", items[:1])]:
                assert json.loads(get("/api" + query, "application/json")) == {"items": expected}
            get("/api?offset=not-an-integer", status=400)
            get("/unknown", status=404)
            get("/../serve.py", status=404)
            print("PASS: offset default/0/1/2/99/-1; invalid offset=400; unknown/traversal=404.", flush=True)

            sample = Path(directory) / "sample.csv"
            sample.write_text(sample.read_text() + "files.example,SecTools Lab teaching data\n")
            updated = list(csv.DictReader(io.StringIO(get("/sample.csv", "text/csv").decode())))
            assert updated[-1]["domain"] == "files.example" and len(updated) == 3
            print("PASS: CSV file edit is visible without restarting the fixture.", flush=True)
            print("PASS: HTTP checks:", checks, flush=True)
        finally:
            process.terminate()
            try:
                process.communicate(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
                process.communicate(timeout=5)
            assert process.poll() is not None
            print("CLEANUP: test subprocess stopped; temporary sample files removed on exit.", flush=True)
    print("SCOPE: local Python HTTP fixture only. Default 0.0.0.0:8090 constructor was intercepted", flush=True)
    print("and bound to 127.0.0.1 with an OS-assigned port; request handler/source content unchanged.", flush=True)
    print("NOT VERIFIED: Docker networking, fixture hostname resolution, OpenCTI Feed Verify/ingestion,", flush=True)
    print("mappers, workers, scheduler, draft/knowledge writes, or OpenCTI offset state progression.", flush=True)
    print("No Docker services, images, networks or existing platform data were changed.", flush=True)


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print("FAIL:", type(error).__name__, str(error), file=sys.stderr)
        sys.exit(1)
