#!/usr/bin/env python3
import cgi
import json
import os
import random
import secrets
import sqlite3
import time
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parent
BACKEND_DIR = BASE_DIR / "backend"
DB_DIR = BACKEND_DIR / "database"
DB_PATH = DB_DIR / "orders.db"
UPLOAD_DIR = BACKEND_DIR / "uploads"
PUBLIC_DIR = BASE_DIR / "frontend"

ORDER_EXPIRY_SECONDS = int(os.getenv("ORDER_EXPIRY_SECONDS", "600"))
ACCOUNT_NAME = os.getenv("PAYMENT_ACCOUNT_NAME", "Your Account Name")
KBZPAY_NUMBER = os.getenv("KBZPAY_NUMBER", "09XXXXXXXXX")
AYAPAY_NUMBER = os.getenv("AYAPAY_NUMBER", "09YYYYYYYYY")
AYAPAY_QR_PATH = os.getenv("AYAPAY_QR_PATH", "/aya-pay-qr.png")
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "")
ADMIN_TOKEN = os.getenv("ADMIN_TOKEN", "change-me")

PRODUCT_MENU = {
    "Mobile Legends": {
        "86 Diamonds": 2500,
        "172 Diamonds": 5000,
        "257 Diamonds": 7500,
        "344 Diamonds": 10000,
        "429 Diamonds": 12500,
        "Weekly Pass": 7000,
        "Monthly Pass": 28000,
    },
    "PUBG Mobile": {
        "60 UC": 3200,
        "325 UC": 15500,
        "660 UC": 31000,
        "1800 UC": 82000,
        "3850 UC": 165000,
        "8100 UC": 330000,
    },
}

STATUSES = {
    "pending",
    "waiting_verification",
    "paid",
    "rejected",
    "completed",
    "expired",
}


def db():
    conn = sqlite3.connect(DB_PATH, timeout=10)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA busy_timeout = 10000")
    return conn


def init_db():
    DB_DIR.mkdir(parents=True, exist_ok=True)
    UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
    PUBLIC_DIR.mkdir(exist_ok=True)
    try:
        with db() as conn:
            try:
                conn.execute("PRAGMA journal_mode = WAL")
            except sqlite3.OperationalError as exc:
                if "locked" not in str(exc).lower():
                    raise
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS orders (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    order_id TEXT NOT NULL UNIQUE,
                    game TEXT NOT NULL,
                    user_game_id TEXT NOT NULL,
                    product TEXT NOT NULL,
                    amount INTEGER NOT NULL,
                    payment_method TEXT,
                    transaction_id TEXT,
                    screenshot TEXT,
                    status TEXT NOT NULL CHECK(status IN (
                        'pending',
                        'waiting_verification',
                        'paid',
                        'rejected',
                        'completed',
                        'expired'
                    )),
                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                )
                """
            )
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS transaction_logs (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    order_id TEXT NOT NULL,
                    action TEXT NOT NULL,
                    detail TEXT,
                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                )
                """
            )
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS order_queue (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    order_id TEXT NOT NULL UNIQUE,
                    status TEXT NOT NULL CHECK(status IN (
                        'waiting',
                        'processing',
                        'completed',
                        'failed'
                    )),
                    attempts INTEGER NOT NULL DEFAULT 0,
                    last_error TEXT,
                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                )
                """
            )
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS smile_accounts (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    email TEXT NOT NULL UNIQUE,
                    cookies TEXT,
                    balance INTEGER NOT NULL DEFAULT 0,
                    status TEXT NOT NULL CHECK(status IN (
                        'active',
                        'paused',
                        'failed'
                    )),
                    last_used TIMESTAMP,
                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                )
                """
            )
    except sqlite3.OperationalError as exc:
        if "locked" not in str(exc).lower():
            raise
        print("Warning: orders.db is locked by another app. Close DB Browser if order creation fails.")


def row_to_dict(row):
    if row is None:
        return None
    data = dict(row)
    data["expires_at"] = created_ts(data["created_at"]) + ORDER_EXPIRY_SECONDS
    data["seconds_remaining"] = max(0, data["expires_at"] - int(time.time()))
    return data


def created_ts(created_at):
    created = datetime.strptime(created_at, "%Y-%m-%d %H:%M:%S")
    return int(created.replace(tzinfo=timezone.utc).timestamp())


def log_action(conn, order_id, action, detail=""):
    conn.execute(
        "INSERT INTO transaction_logs (order_id, action, detail) VALUES (?, ?, ?)",
        (order_id, action, detail),
    )


def enqueue_paid_order(conn, order_id):
    conn.execute(
        """
        INSERT INTO order_queue (order_id, status)
        VALUES (?, 'waiting')
        ON CONFLICT(order_id) DO UPDATE SET
            status = CASE
                WHEN order_queue.status IN ('completed', 'processing') THEN order_queue.status
                ELSE 'waiting'
            END,
            updated_at = CURRENT_TIMESTAMP
        """,
        (order_id,),
    )
    log_action(conn, order_id, "queued", "Order is waiting for Smile.one automation")


def update_queue_status(order_id, status, detail=""):
    if status not in {"waiting", "processing", "completed", "failed"}:
        raise ValueError("Invalid queue status")
    with db() as conn:
        queue_row = conn.execute(
            "SELECT * FROM order_queue WHERE order_id = ?",
            (order_id,),
        ).fetchone()
        if queue_row is None:
            return None
        if status == "processing":
            conn.execute(
                """
                UPDATE order_queue
                SET status = ?, attempts = attempts + 1, last_error = NULL, updated_at = CURRENT_TIMESTAMP
                WHERE order_id = ?
                """,
                (status, order_id),
            )
        else:
            conn.execute(
                """
                UPDATE order_queue
                SET status = ?, last_error = ?, updated_at = CURRENT_TIMESTAMP
                WHERE order_id = ?
                """,
                (status, detail, order_id),
            )
        if status == "completed":
            conn.execute("UPDATE orders SET status = 'completed' WHERE order_id = ?", (order_id,))
            log_action(conn, order_id, "completed", detail or "automation completed")
        elif status == "failed":
            log_action(conn, order_id, "automation_failed", detail)
        elif status == "processing":
            log_action(conn, order_id, "automation_processing", detail)
        elif status == "waiting":
            log_action(conn, order_id, "automation_retry", detail)
        return dict(
            conn.execute("SELECT * FROM order_queue WHERE order_id = ?", (order_id,)).fetchone()
        )


def expire_old_orders():
    cutoff = int(time.time()) - ORDER_EXPIRY_SECONDS
    with db() as conn:
        rows = conn.execute(
            "SELECT order_id FROM orders WHERE status = 'pending' AND strftime('%s', created_at) < ?",
            (cutoff,),
        ).fetchall()
        for row in rows:
            conn.execute(
                "UPDATE orders SET status = 'expired' WHERE order_id = ?",
                (row["order_id"],),
            )
            log_action(conn, row["order_id"], "expired", "Payment upload window elapsed")


def get_order(order_id):
    expire_old_orders()
    with db() as conn:
        return row_to_dict(
            conn.execute("SELECT * FROM orders WHERE order_id = ?", (order_id,)).fetchone()
        )


def unique_order_id():
    return f"ORD{int(time.time())}{random.randint(100, 999)}"


def final_amount(product):
    base = None
    for products in PRODUCT_MENU.values():
        if product in products:
            base = products[product]
            break
    if base is None:
        raise ValueError("Unknown product")
    return base + random.randint(11, 89)


def send_telegram(order):
    if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
        return

    caption = (
        f"Payment waiting verification\n"
        f"Order: {order['order_id']}\n"
        f"Amount: {order['amount']} MMK\n"
        f"Method: {order['payment_method']}\n"
        f"Game: {order['game']}\n"
        f"User ID: {order['user_game_id']}\n"
        f"Product: {order['product']}\n"
        f"Txn ID: {order.get('transaction_id') or '-'}\n\n"
        "Verify inside KBZPay/AYA Pay before confirming."
    )
    keyboard = {
        "inline_keyboard": [
            [
                {"text": "Confirm", "callback_data": f"confirm:{order['order_id']}"},
                {"text": "Reject", "callback_data": f"reject:{order['order_id']}"},
            ],
            [{"text": "Completed", "callback_data": f"complete:{order['order_id']}"}],
        ]
    }

    screenshot_path = BASE_DIR / order["screenshot"]
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto"
    boundary = f"----codex{secrets.token_hex(8)}"
    body = multipart_body(
        boundary,
        {
            "chat_id": TELEGRAM_CHAT_ID,
            "caption": caption,
            "reply_markup": json.dumps(keyboard),
        },
        "photo",
        screenshot_path,
    )
    request = urllib.request.Request(
        url,
        data=body,
        headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
    )
    try:
        urllib.request.urlopen(request, timeout=10).read()
    except Exception as exc:
        with db() as conn:
            log_action(conn, order["order_id"], "telegram_failed", str(exc))


def multipart_body(boundary, fields, file_field, file_path):
    chunks = []
    for name, value in fields.items():
        chunks.append(f"--{boundary}\r\n".encode())
        chunks.append(f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode())
        chunks.append(str(value).encode())
        chunks.append(b"\r\n")
    chunks.append(f"--{boundary}\r\n".encode())
    chunks.append(
        f'Content-Disposition: form-data; name="{file_field}"; filename="{file_path.name}"\r\n'.encode()
    )
    chunks.append(b"Content-Type: image/jpeg\r\n\r\n")
    chunks.append(file_path.read_bytes())
    chunks.append(b"\r\n")
    chunks.append(f"--{boundary}--\r\n".encode())
    return b"".join(chunks)


def telegram_answer_callback(callback_id, text):
    if not TELEGRAM_BOT_TOKEN or not callback_id:
        return
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/answerCallbackQuery"
    data = urllib.parse.urlencode({"callback_query_id": callback_id, "text": text}).encode()
    try:
        urllib.request.urlopen(url, data=data, timeout=10).read()
    except Exception:
        pass


def send_telegram_text(text):
    if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
        return
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    data = urllib.parse.urlencode({"chat_id": TELEGRAM_CHAT_ID, "text": text}).encode()
    try:
        urllib.request.urlopen(url, data=data, timeout=10).read()
    except Exception:
        pass


def update_order_status(order_id, status, detail=""):
    if status not in STATUSES:
        raise ValueError("Invalid status")
    with db() as conn:
        order = conn.execute("SELECT * FROM orders WHERE order_id = ?", (order_id,)).fetchone()
        if order is None:
            return None
        conn.execute("UPDATE orders SET status = ? WHERE order_id = ?", (status, order_id))
        if status == "paid":
            enqueue_paid_order(conn, order_id)
        log_action(conn, order_id, status, detail)
        fresh = row_to_dict(
            conn.execute("SELECT * FROM orders WHERE order_id = ?", (order_id,)).fetchone()
        )
    if status == "paid":
        send_telegram_text(f"{order_id} is paid and ready to process on Smile.one.")
    elif status == "rejected":
        send_telegram_text(f"{order_id} was rejected. Do not process this order.")
    elif status == "completed":
        send_telegram_text(f"{order_id} has been marked completed.")
    return fresh


class Handler(BaseHTTPRequestHandler):
    def do_HEAD(self):
        parsed = urllib.parse.urlparse(self.path)
        if parsed.path == "/":
            return self.head_file(PUBLIC_DIR / "index.html", "text/html")
        if parsed.path.startswith("/uploads/"):
            return self.head_file(UPLOAD_DIR / parsed.path.removeprefix("/uploads/"), guess_type(parsed.path))
        if parsed.path.startswith("/"):
            return self.head_file(PUBLIC_DIR / parsed.path.lstrip("/"), guess_type(parsed.path))
        self.send_response(HTTPStatus.NOT_FOUND)
        self.end_headers()

    def do_GET(self):
        expire_old_orders()
        parsed = urllib.parse.urlparse(self.path)
        if parsed.path == "/":
            return self.serve_file(PUBLIC_DIR / "index.html", "text/html")
        if parsed.path == "/api/config":
            return self.json(
                {
                    "account_name": ACCOUNT_NAME,
                    "kbzpay_number": KBZPAY_NUMBER,
                    "ayapay_number": AYAPAY_NUMBER,
                    "ayapay_qr_path": AYAPAY_QR_PATH,
                    "menu": PRODUCT_MENU,
                    "expiry_seconds": ORDER_EXPIRY_SECONDS,
                }
            )
        if parsed.path.startswith("/api/orders/"):
            order_id = parsed.path.rsplit("/", 1)[-1]
            order = get_order(order_id)
            if not order:
                return self.error(HTTPStatus.NOT_FOUND, "Order not found")
            return self.json({"order": order})
        if parsed.path == "/api/admin/orders":
            if not self.is_admin(parsed):
                return self.error(HTTPStatus.UNAUTHORIZED, "Invalid admin token")
            with db() as conn:
                rows = conn.execute(
                    "SELECT * FROM orders ORDER BY id DESC LIMIT 100"
                ).fetchall()
            return self.json({"orders": [row_to_dict(row) for row in rows]})
        if parsed.path == "/api/admin/queue":
            if not self.is_admin(parsed):
                return self.error(HTTPStatus.UNAUTHORIZED, "Invalid admin token")
            with db() as conn:
                rows = conn.execute(
                    """
                    SELECT q.*, o.game, o.user_game_id, o.product, o.amount
                    FROM order_queue q
                    JOIN orders o ON o.order_id = q.order_id
                    ORDER BY q.id ASC
                    LIMIT 100
                    """
                ).fetchall()
            return self.json({"queue": [dict(row) for row in rows]})
        if parsed.path == "/api/admin/smile-accounts":
            if not self.is_admin(parsed):
                return self.error(HTTPStatus.UNAUTHORIZED, "Invalid admin token")
            with db() as conn:
                rows = conn.execute(
                    """
                    SELECT id, email, balance, status, last_used, created_at, updated_at
                    FROM smile_accounts
                    ORDER BY status ASC, last_used ASC, id ASC
                    """
                ).fetchall()
            return self.json({"accounts": [dict(row) for row in rows]})
        if parsed.path.startswith("/uploads/"):
            return self.serve_file(UPLOAD_DIR / parsed.path.removeprefix("/uploads/"), guess_type(parsed.path))
        if parsed.path.startswith("/"):
            return self.serve_file(PUBLIC_DIR / parsed.path.lstrip("/"), guess_type(parsed.path))
        return self.error(HTTPStatus.NOT_FOUND, "Not found")

    def do_POST(self):
        expire_old_orders()
        parsed = urllib.parse.urlparse(self.path)
        if parsed.path == "/api/orders":
            return self.create_order()
        if parsed.path.startswith("/api/orders/") and parsed.path.endswith("/payment"):
            order_id = parsed.path.split("/")[3]
            return self.upload_payment(order_id)
        if parsed.path == "/api/telegram/webhook":
            return self.telegram_webhook()
        if parsed.path.startswith("/api/admin/orders/"):
            if not self.is_admin(parsed):
                return self.error(HTTPStatus.UNAUTHORIZED, "Invalid admin token")
            parts = parsed.path.split("/")
            if len(parts) == 6 and parts[5] in {"confirm", "reject", "complete"}:
                status = {"confirm": "paid", "reject": "rejected", "complete": "completed"}[parts[5]]
                order = update_order_status(parts[4], status, "admin panel action")
                if not order:
                    return self.error(HTTPStatus.NOT_FOUND, "Order not found")
                return self.json({"order": order})
        if parsed.path.startswith("/api/admin/queue/"):
            if not self.is_admin(parsed):
                return self.error(HTTPStatus.UNAUTHORIZED, "Invalid admin token")
            parts = parsed.path.split("/")
            if len(parts) == 6 and parts[5] in {"process", "complete", "fail", "retry"}:
                payload = self.read_json()
                detail = (payload.get("detail") or "").strip()
                status = {
                    "process": "processing",
                    "complete": "completed",
                    "fail": "failed",
                    "retry": "waiting",
                }[parts[5]]
                queue_item = update_queue_status(parts[4], status, detail)
                if not queue_item:
                    return self.error(HTTPStatus.NOT_FOUND, "Queue item not found")
                return self.json({"queue_item": queue_item})
        return self.error(HTTPStatus.NOT_FOUND, "Not found")

    def create_order(self):
        payload = self.read_json()
        game = payload.get("game", "").strip()
        user_game_id = payload.get("user_game_id", "").strip()
        product = payload.get("product", "").strip()
        if not game or not user_game_id or not product:
            return self.error(HTTPStatus.BAD_REQUEST, "game, user_game_id, and product are required")
        if game not in PRODUCT_MENU or product not in PRODUCT_MENU[game]:
            return self.error(HTTPStatus.BAD_REQUEST, "Selected product is not available for this game")
        try:
            amount = final_amount(product)
        except ValueError as exc:
            return self.error(HTTPStatus.BAD_REQUEST, str(exc))

        order_id = unique_order_id()
        try:
            with db() as conn:
                conn.execute(
                    """
                    INSERT INTO orders (order_id, game, user_game_id, product, amount, status)
                    VALUES (?, ?, ?, ?, ?, 'pending')
                    """,
                    (order_id, game, user_game_id, product, amount),
                )
                log_action(conn, order_id, "created", f"{product} for {user_game_id}")
        except sqlite3.OperationalError as exc:
            if "locked" in str(exc).lower():
                return self.error(
                    HTTPStatus.SERVICE_UNAVAILABLE,
                    "Database is locked. Close DB Browser or any app currently editing orders.db, then try again.",
                )
            raise
        return self.json({"order_id": order_id, "amount": amount})

    def upload_payment(self, order_id):
        order = get_order(order_id)
        if not order:
            return self.error(HTTPStatus.NOT_FOUND, "Order not found")
        if order["status"] == "expired":
            return self.error(HTTPStatus.GONE, "Order expired")
        if order["status"] not in {"pending", "rejected"}:
            return self.error(HTTPStatus.CONFLICT, "Payment upload is not available for this order")

        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={
                "REQUEST_METHOD": "POST",
                "CONTENT_TYPE": self.headers.get("Content-Type"),
            },
        )
        payment_method = (form.getfirst("payment_method") or "").strip()
        transaction_id = (form.getfirst("transaction_id") or "").strip()
        if payment_method not in {"KBZPay", "AYA Pay"}:
            return self.error(HTTPStatus.BAD_REQUEST, "Invalid payment method")
        file_item = form["screenshot"] if "screenshot" in form else None
        if file_item is None or not file_item.filename:
            return self.error(HTTPStatus.BAD_REQUEST, "Screenshot is required")

        extension = Path(file_item.filename).suffix.lower()
        if extension not in {".jpg", ".jpeg", ".png", ".webp"}:
            return self.error(HTTPStatus.BAD_REQUEST, "Screenshot must be jpg, png, or webp")
        safe_name = f"{order_id}-{secrets.token_hex(6)}{extension}"
        output_path = UPLOAD_DIR / safe_name
        with output_path.open("wb") as fh:
            fh.write(file_item.file.read())
        relative_path = f"uploads/{safe_name}"

        with db() as conn:
            conn.execute(
                """
                UPDATE orders
                SET screenshot = ?, payment_method = ?, transaction_id = ?, status = 'waiting_verification'
                WHERE order_id = ?
                """,
                (relative_path, payment_method, transaction_id, order_id),
            )
            log_action(conn, order_id, "screenshot_uploaded", payment_method)
            fresh = row_to_dict(
                conn.execute("SELECT * FROM orders WHERE order_id = ?", (order_id,)).fetchone()
            )
        send_telegram(fresh)
        return self.json({"order": fresh})

    def telegram_webhook(self):
        payload = self.read_json()
        callback = payload.get("callback_query") or {}
        data = callback.get("data", "")
        callback_id = callback.get("id")
        if ":" not in data:
            return self.json({"ok": True})
        action, order_id = data.split(":", 1)
        status_map = {"confirm": "paid", "reject": "rejected", "complete": "completed"}
        if action not in status_map:
            return self.json({"ok": True})
        status = status_map[action]
        detail = "telegram callback"
        order = update_order_status(order_id, status, detail)
        telegram_answer_callback(callback_id, f"{order_id} marked {status}" if order else "Order not found")
        return self.json({"ok": bool(order), "order": order})

    def read_json(self):
        length = int(self.headers.get("Content-Length", "0"))
        if length == 0:
            return {}
        return json.loads(self.rfile.read(length).decode())

    def is_admin(self, parsed):
        params = urllib.parse.parse_qs(parsed.query)
        token = params.get("token", [""])[0]
        return secrets.compare_digest(token, ADMIN_TOKEN)

    def serve_file(self, path, content_type):
        try:
            resolved = path.resolve()
            if not str(resolved).startswith(str(BASE_DIR)):
                return self.error(HTTPStatus.FORBIDDEN, "Forbidden")
            data = resolved.read_bytes()
        except FileNotFoundError:
            return self.error(HTTPStatus.NOT_FOUND, "Not found")
        self.send_response(HTTPStatus.OK)
        self.send_header("Content-Type", content_type)
        if resolved.parent == PUBLIC_DIR:
            self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def head_file(self, path, content_type):
        try:
            resolved = path.resolve()
            if not str(resolved).startswith(str(BASE_DIR)):
                self.send_response(HTTPStatus.FORBIDDEN)
                self.end_headers()
                return
            size = resolved.stat().st_size
        except FileNotFoundError:
            self.send_response(HTTPStatus.NOT_FOUND)
            self.end_headers()
            return
        self.send_response(HTTPStatus.OK)
        self.send_header("Content-Type", content_type)
        if resolved.parent == PUBLIC_DIR:
            self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(size))
        self.end_headers()

    def json(self, payload, status=HTTPStatus.OK):
        data = json.dumps(payload).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def error(self, status, message):
        return self.json({"error": message}, status)

    def log_message(self, fmt, *args):
        print(f"{self.address_string()} - {fmt % args}")


def guess_type(path):
    if path.endswith(".html"):
        return "text/html"
    if path.endswith(".css"):
        return "text/css"
    if path.endswith(".js"):
        return "application/javascript"
    if path.endswith(".png"):
        return "image/png"
    if path.endswith(".jpg") or path.endswith(".jpeg"):
        return "image/jpeg"
    if path.endswith(".webp"):
        return "image/webp"
    if path.endswith(".svg"):
        return "image/svg+xml"
    return "application/octet-stream"


if __name__ == "__main__":
    init_db()
    port = int(os.getenv("PORT", "8000"))
    server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
    print(f"Server running at http://127.0.0.1:{port}")
    server.serve_forever()
