#!/usr/bin/python3
import http.server
import json
import subprocess
import tempfile
import threading
from pathlib import Path

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        body = b"<html><head><title>gowitness-autopkgtest</title></head><body>Local fixture</body></html>"
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass

with tempfile.TemporaryDirectory() as directory:
    path = Path(directory)
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    try:
        subprocess.run(["gowitness", "scan", "single", "--chrome-path", "/usr/bin/chromium",
                        "--url", f"http://127.0.0.1:{server.server_port}/", "--delay", "0",
                        "--screenshot-format", "png", "--screenshot-path", str(path / "screenshots"),
                        "--write-jsonl", "--write-jsonl-file", str(path / "results.jsonl")],
                       cwd=directory, check=True, timeout=90)
        rows = [json.loads(line) for line in (path / "results.jsonl").read_text().splitlines()]
        assert any(row["response_code"] == 200 and row["title"] == "gowitness-autopkgtest"
                   for row in rows), rows
        images = list((path / "screenshots").glob("*.png"))
        assert images, "No screenshot was saved"
        assert all(image.read_bytes().startswith(b"\x89PNG\r\n\x1a\n") for image in images)
    finally:
        server.shutdown()
        server.server_close()
