import json
from datetime import datetime, timezone
from email.utils import format_datetime
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlsplit

ROOT = Path(__file__).resolve().parent
ITEMS = [
    {"id": "lab-domain-1", "domain": "login.example"},
    {"id": "lab-domain-2", "domain": "mail.example"},
]
CSV = "domain,source_note\nlogin.example,SecTools Lab teaching data\nmail.example,SecTools Lab teaching data\n"
RSS = f'''<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"><channel>
<title>SecTools Lab local feed</title>
<link>http://fixture:8090/article.html</link>
<description>Local teaching fixture</description>
<item><title>SecTools Lab RSS exercise</title>
<guid isPermaLink="false">sectools-lab-rss-001</guid>
<link>http://fixture:8090/article.html</link>
<pubDate>{format_datetime(datetime.now(timezone.utc))}</pubDate>
<description>login.example is a teaching value; its role is unknown.</description>
</item></channel></rss>'''
ROOT.joinpath("sample.csv").write_text(CSV, encoding="utf-8")
ROOT.joinpath("sample.json").write_text(json.dumps({"items": ITEMS}), encoding="utf-8")
ROOT.joinpath("sample.xml").write_text(RSS, encoding="utf-8")

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        request = urlsplit(self.path)
        if request.path == "/api":
            raw = parse_qs(request.query).get("offset", ["0"])[0]
            try:
                offset = max(0, int(raw))
            except ValueError:
                self.send_error(400, "offset must be an integer")
                return
            body = json.dumps({"items": ITEMS[offset:offset + 1]}).encode()
            mime = "application/json"
        elif request.path == "/article.html":
            body = b"<h1>SecTools Lab</h1><p>Teaching data only. Domain role unknown.</p>"
            mime = "text/html"
        else:
            files = {"/sample.csv": ("sample.csv", "text/csv"),
                     "/sample.json": ("sample.json", "application/json"),
                     "/sample.xml": ("sample.xml", "application/rss+xml")}
            if request.path not in files:
                self.send_error(404)
                return
            filename, mime = files[request.path]
            body = ROOT.joinpath(filename).read_bytes()
        self.send_response(200)
        self.send_header("Content-Type", mime + "; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

HTTPServer(("0.0.0.0", 8090), Handler).serve_forever()
