"""Local SDK workshop: a catalogue and transactional reservations."""
from argparse import ArgumentParser
from contextlib import closing
from html import escape
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import secrets
import sqlite3
from urllib.parse import parse_qs

from yeti3_core import Engine, Module, ModuleManifest


class Inventory(Module):
    manifest = ModuleManifest(
        id="workshop.inventory", name="Каталог мастерской", version="1.0.0",
        provides=("workshop.inventory",),
    )

    def __init__(self, path):
        self.path = path

    def register(self, engine):
        engine.provide("workshop.inventory", self, module_id=self.manifest.id)

    def boot(self, engine):
        with closing(sqlite3.connect(self.path)) as db, db:
            db.executescript("""
                CREATE TABLE IF NOT EXISTS products (
                    id INTEGER PRIMARY KEY, title TEXT NOT NULL,
                    price INTEGER NOT NULL, stock INTEGER NOT NULL CHECK (stock >= 0)
                );
                CREATE TABLE IF NOT EXISTS reservations (
                    id INTEGER PRIMARY KEY, product INTEGER NOT NULL REFERENCES products(id),
                    price INTEGER NOT NULL
                );
                INSERT OR IGNORE INTO products VALUES
                    (1, 'Настольный светильник', 4900, 2),
                    (2, 'Полка из дуба', 3200, 3);
            """)

    def list_products(self):
        with closing(sqlite3.connect(self.path)) as db:
            return db.execute("SELECT id, title, price, stock FROM products ORDER BY id").fetchall()

    def reserve(self, product):
        with closing(sqlite3.connect(self.path)) as db, db:
            db.execute("PRAGMA foreign_keys = ON")
            row = db.execute(
                "UPDATE products SET stock = stock - 1 WHERE id = ? AND stock > 0 RETURNING price",
                (product,),
            ).fetchone()
            if row is None:
                return None
            return db.execute(
                "INSERT INTO reservations (product, price) VALUES (?, ?)", (product, row[0]),
            ).lastrowid


def inventory(path):
    engine = Engine()
    engine.register(Inventory(path))
    engine.boot()
    return engine.capabilities.get("workshop.inventory")


def product_card(product, token):
    product_id, title, price, stock = product
    button = (
        f'<form method="post" action="/reserve"><input type="hidden" name="token" value="{token}">'
        f'<input type="hidden" name="id" value="{product_id}"><button>Забронировать</button></form>'
        if stock else '<p class="sold">Нет в наличии</p>'
    )
    return f'<article><h2>{escape(title)}</h2><p>{price:,} ₽ · остаток {stock}</p>{button}</article>'


def serve(store, port):
    token = secrets.token_urlsafe(24)
    css = Path(__file__).parent / "asset_pack/static/shop.css"

    class Workshop(BaseHTTPRequestHandler):
        def allowed_host(self):
            return self.headers.get("Host") in {f"127.0.0.1:{port}", f"localhost:{port}"}

        def respond(self, status, content, kind="text/html; charset=utf-8"):
            self.send_response(status)
            self.send_header("Content-Type", kind)
            self.send_header("Content-Length", str(len(content)))
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(content)

        def do_GET(self):
            if not self.allowed_host():
                self.send_error(400)
            elif self.path == "/shop.css":
                self.respond(200, css.read_bytes(), "text/css; charset=utf-8")
            elif self.path == "/":
                cards = "".join(product_card(row, token) for row in store.list_products())
                page = f"""<!doctype html><html lang="ru"><meta charset="utf-8">
                    <meta name="viewport" content="width=device-width,initial-scale=1">
                    <title>Каталог мастерской</title><link rel="stylesheet" href="/shop.css">
                    <main><header><h1>Каталог мастерской</h1><p>Учебный магазин с резервированием.</p></header>
                    <section>{cards}</section></main></html>"""
                self.respond(200, page.encode())
            else:
                self.send_error(404)

        def do_POST(self):
            if not self.allowed_host() or self.path != "/reserve":
                self.send_error(404)
                return
            try:
                length = int(self.headers.get("Content-Length", "0"))
                if not 0 < length <= 1024 or self.headers.get_content_type() != "application/x-www-form-urlencoded":
                    raise ValueError
                form = parse_qs(self.rfile.read(length).decode(), strict_parsing=True, max_num_fields=2)
                if form.get("token") != [token] or set(form) != {"token", "id"} or len(form["id"]) != 1:
                    raise ValueError
                product = int(form["id"][0])
                if not 0 < product <= 2**63 - 1:
                    raise ValueError
            except ValueError:
                self.send_error(400)
                return
            reservation = store.reserve(product)
            message = f"Бронь №{reservation} сохранена." if reservation else "Товар закончился."
            self.respond(201 if reservation else 409,
                         f'<!doctype html><meta charset="utf-8"><p>{message}</p><a href="/">В каталог</a>'.encode())

    with ThreadingHTTPServer(("127.0.0.1", port), Workshop) as server:
        print(f"http://127.0.0.1:{port}", flush=True)
        server.serve_forever()


if __name__ == "__main__":
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=8088)
    parser.add_argument("--database", type=Path, default=Path("workshop.sqlite3"))
    args = parser.parse_args()
    serve(inventory(args.database), args.port)
