"""Replay Boxsti's fictional CRM integration demo. Run with Python 3.9+."""
import json
import re
import sqlite3
import sys
from contextlib import closing
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener

FIELDS = ("email", "full_name", "organization")
SAMPLE = {"contact_email": "Maya@north.example", "name": "Maya Chen", "company": "North Supply"}
CASES = [
    ("First inquiry", SAMPLE, 201, "created"),
    ("Same inquiry delivered again", dict(SAMPLE, contact_email=" maya@north.example "), 200, "unchanged"),
    ("Company name corrected", dict(SAMPLE, company="North Supply Co."), 200, "updated"),
    ("Inquiry missing an email", {"name": "Sam Lee", "company": "Cedar Parts"}, 422, "rejected"),
    ("Second valid inquiry", {"contact_email": "sam@cedar.example", "name": "Sam Lee", "company": "Cedar Parts"}, 201, "created"),
]


def save_contact(db, fields):
    email, name, organization = (fields.get(key) for key in FIELDS)
    if not all(isinstance(value, str) and value.strip() for value in (email, name, organization)):
        return 422, {"outcome": "rejected", "reason": "Email, name and organization are required"}
    email, name, organization = email.strip().casefold(), name.strip(), organization.strip()
    if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
        return 422, {"outcome": "rejected", "reason": "Invalid email format"}
    with db:
        current = db.execute("SELECT id, full_name, organization FROM contacts WHERE email = ?", (email,)).fetchone()
        if current is None:
            row = db.execute("INSERT INTO contacts(email, full_name, organization) VALUES (?, ?, ?)", (email, name, organization))
            return 201, {"outcome": "created", "contact_id": row.lastrowid}
        if tuple(current)[1:] == (name, organization):
            return 200, {"outcome": "unchanged", "contact_id": current["id"]}
        db.execute("UPDATE contacts SET full_name = ?, organization = ? WHERE id = ?", (name, organization, current["id"]))
        return 200, {"outcome": "updated", "contact_id": current["id"]}


class SandboxCRM(BaseHTTPRequestHandler):
    def reply(self, status, body):
        payload = json.dumps(body, ensure_ascii=False).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_POST(self):
        if self.path != "/contacts":
            return self.reply(404, {"error": "Unknown endpoint"})
        size = int(self.headers.get("Content-Length", 0))
        if size > 16384:
            return self.reply(413, {"error": "Too large"})
        try:
            fields = json.loads(self.rfile.read(size))
        except (ValueError, UnicodeError):
            return self.reply(400, {"error": "Invalid JSON"})
        if not isinstance(fields, dict):
            return self.reply(400, {"error": "Expected an object"})
        self.reply(*save_contact(self.server.db, fields))

    def do_GET(self):
        if self.path != "/contacts":
            return self.reply(404, {"error": "Unknown endpoint"})
        records = self.server.db.execute("SELECT * FROM contacts ORDER BY id")
        self.reply(200, {"contacts": [dict(row) for row in records]})

    def log_message(self, *args):
        pass


def request(client, url, body=None):
    data = None if body is None else json.dumps(body).encode()
    req = Request(url, data=data, headers={"Content-Type": "application/json"})
    try:
        response = client.open(req, timeout=5)
    except HTTPError as error:
        response = error
    with response:
        return response.status, json.load(response)


def run_demo():
    with closing(sqlite3.connect(":memory:", check_same_thread=False)) as db:
        db.row_factory = sqlite3.Row
        db.execute("CREATE TABLE contacts (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, full_name TEXT NOT NULL, organization TEXT NOT NULL)")
        with HTTPServer(("127.0.0.1", 0), SandboxCRM) as server:
            server.db = db
            thread = Thread(target=server.serve_forever, daemon=True)
            thread.start()
            try:
                url = f"http://127.0.0.1:{server.server_port}/contacts"
                client = build_opener(ProxyHandler({}))
                receipts = []
                for label, inquiry, expected_status, expected_outcome in CASES:
                    mapped = {"email": inquiry.get("contact_email"), "full_name": inquiry.get("name"), "organization": inquiry.get("company")}
                    status, response = request(client, url, mapped)
                    if (status, response.get("outcome")) != (expected_status, expected_outcome):
                        raise RuntimeError(f"Unexpected API response for {label}: {status}, {response}")
                    receipts.append({"case": label, "inquiry": inquiry, "api_request": mapped, "http_status": status, "response": response})
                status, result = request(client, url)
                expected = [
                    {"id": 1, "email": "maya@north.example", "full_name": "Maya Chen", "organization": "North Supply Co."},
                    {"id": 2, "email": "sam@cedar.example", "full_name": "Sam Lee", "organization": "Cedar Parts"},
                ]
                if status != 200 or result["contacts"] != expected or [item["response"].get("contact_id") for item in receipts] != [1, 1, 1, None, 2]:
                    raise RuntimeError("Contact read-back or identifiers failed validation")
                return {"environment": "Boxsti local sandbox CRM with fictional data", "write_endpoint": "POST /contacts", "read_endpoint": "GET /contacts", "requests": receipts, "read_back": result["contacts"]}
            finally:
                server.shutdown()
                thread.join()


if __name__ == "__main__":
    json.dump(run_demo(), sys.stdout, indent=2, ensure_ascii=False)
    print()
