"""V4: files planted on a local server, read through scan.py's own fetch code. Usage: python -B fixtures.py"""
import http.server, json, os, sys, threading
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import rule, scan

HERE = os.path.dirname(os.path.abspath(__file__))
# The eight required fields of A2A 1.0.0, section 4.4.1.
A2A = {"name": "a", "description": "d", "supportedInterfaces": [{"url": "https://x/a2a", "protocolBinding": "JSONRPC"}],
       "version": "1", "capabilities": {}, "defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain"], "skills": []}
MCP = {"name": "m", "version": "1", "remotes": [{"type": "streamable-http", "url": "https://x/mcp"}]}
MINIMAL = open(os.path.join(HERE, "fixtures/minimal.json"), "rb").read()
TEMPLATED = open(os.path.join(HERE, "fixtures/templated-remote.json"), "rb").read()
PLANT = {
    "good": {rule.CONTROL: (404, b"no"), "/.well-known/mcp/server-card.json": (200, json.dumps(MCP).encode()),
             "/.well-known/api-catalog": (200, b'{"linkset":[{"anchor":"https://x/"}]}'),
             "/.well-known/ai-catalog.json": (200, json.dumps({"specVersion": "1.0", "entries": [
                 {"identifier": "i", "type": rule.MCP_CARD_TYPE, "url": "https://x"}]}).encode()),
             "/.well-known/agent-card.json": (200, json.dumps(A2A).encode()),
             "/.well-known/agent.json": (200, json.dumps(A2A).encode()),
             "/llms.txt": (200, b"# Title\n\n> a site\n")},
    "minimal": {rule.CONTROL: (404, b"no"), "/.well-known/mcp/server-card.json": (200, MINIMAL)},
    "templated": {rule.CONTROL: (404, b"no"), "/.well-known/mcp/server-card.json": (200, TEMPLATED)},
    "html200": {rule.CONTROL: (200, b"<html>home</html>"), "/llms.txt": (200, b"<html>home2</html>"),
                "/.well-known/mcp/server-card.json": (200, b"<html>home3</html>")},
    "catchall": {"*": (200, json.dumps(MCP).encode())},
    "wrongjson": {rule.CONTROL: (404, b""), "/.well-known/mcp/server-card.json": (200, b'{"name":"x"}'),
                  "/.well-known/api-catalog": (200, b'{"linkset":[]}'), "/.well-known/agent-card.json": (200, b'{"name":"x"}'),
                  "/.well-known/ai-catalog.json": (200, b'[]')},
}
WANT = {"good": set(rule.PATHS), "minimal": {"mcp_card"}, "templated": {"mcp_card"}, "html200": set(), "catchall": set(), "wrongjson": set()}


class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        site, path = self.path.split("/", 2)[1], "/" + self.path.split("/", 2)[2]
        table = PLANT[site]
        code, body = table.get(path, table.get("*", (404, b"nope")))
        self.send_response(code); self.send_header("Content-Length", str(len(body))); self.end_headers()
        self.wfile.write(body)

    def log_message(self, *a):
        pass


def main():
    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    bad = 0
    for site, want in WANT.items():
        row = scan.scan_host(f"http://127.0.0.1:{srv.server_port}/{site}")
        got = {k for k, p in row["paths"].items() if p["ok"]}
        if got != want:
            bad += 1
        print(site, "OK" if got == want else f"WRONG got {sorted(got)}")
    dead = scan.scan_host("http://127.0.0.1:1")
    print("dead", "OK" if dead is None else "WRONG")
    srv.shutdown()
    print("V4", "PASS" if not bad and dead is None else "FAIL")
    return 1 if bad or dead is not None else 0


if __name__ == "__main__":
    sys.exit(main())
