"""A stand-in for the HBank merchant API (/api/v1), for testing the SDKs without a database.

    python sdks/testing/mock_server.py [--port 8765]

Accepts the API key "test_key". State lives in memory and is lost on exit. It mirrors the real API's request
validation, status codes, error codes and response shapes (see MerchantApiController.cs), including 7-digit
fractional seconds in timestamps, as System.Text.Json writes them. It does not charge anyone: POST
/_mock/pay/{transaction_id} marks a payment completed so refunds can be tested.
"""

import argparse
import json
import re
import secrets
import string
import threading
from datetime import datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

API_KEY = "test_key"
BASE = "http://127.0.0.1"
DECIMALS = {"EUR": 2, "USD": 2, "CHF": 2, "GBP": 2, "SEK": 2, "DKK": 2, "JPY": 0}
RATES = {"EUR": Decimal("1"), "USD": Decimal("1.0837"), "CHF": Decimal("0.9312"), "GBP": Decimal("0.8421"),
         "SEK": Decimal("11.42"), "DKK": Decimal("7.46"), "JPY": Decimal("162.3")}
INTERVALS = ("day", "week", "month", "year")

lock = threading.Lock()
transactions: dict[str, dict] = {}
subscriptions: dict[str, dict] = {}
next_id = [7300]


def new_id() -> int:
    next_id[0] += 1
    return next_id[0]


def new_subscription_id() -> str:
    """"sub_" and 24 random letters and digits, like the real ones."""
    return "sub_" + "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(24))


def new_transaction_id() -> str:
    """Like the real ones: "tx_" and 24 random letters and digits, never a number that counts up."""
    return "tx_" + "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(24))


def stamp(dt: datetime | None) -> str | None:
    return None if dt is None else dt.strftime("%Y-%m-%dT%H:%M:%S.%f") + "1Z"


def number(value) -> Decimal | None:
    if isinstance(value, bool) or value is None:
        return None
    try:
        return Decimal(str(value).strip()) if isinstance(value, (int, float, str, Decimal)) else None
    except InvalidOperation:
        return None


def round_to(amount: Decimal, currency: str) -> Decimal:
    return amount.quantize(Decimal(1).scaleb(-DECIMALS[currency]))


def details(t: dict) -> dict:
    refundable = t["amount"] - t["refunded"] if t["type"] == "payment" and t["status"] == "completed" else Decimal(0)
    return {"id": t["id"], "type": t["type"], "amount": t["amount"], "currency": t["currency"], "status": t["status"],
            "description": t["description"], "reference": t["reference"], "payment_code": t["payment_code"],
            "refunded": t["refunded"], "refundable": refundable, "refund_of": t["refund_of"],
            "subscription_id": t["subscription_id"], "subscription_ids": t.get("subscription_ids") or
            ([t["subscription_id"]] if t["subscription_id"] else [])}


def subscription_json(s: dict) -> dict:
    url = f"{BASE}/s/{s['code']}"
    return {"id": s["id"], "status": s["status"], "active_period": s["status"] == "active",
            "amount": s["amount"], "currency": s["currency"], "interval": s["interval"],
            "interval_count": s["interval_count"], "description": s["description"], "url": url, "qr_svg": url + "/qr.svg",
            "subscribed_at": stamp(s["started_at"]), "subscribed_for_days": 0 if s["started_at"] else None,
            "subscribed_for_seconds": 5 if s["started_at"] else None, "canceled": s["canceled_at"] is not None,
            "canceled_at": stamp(s["canceled_at"]), "canceled_by": s["canceled_by"],
            "current_period_start": None, "current_period_end": None, "next_charge_at": None, "ends_at": None,
            "last_day": None, "charges": 0, "last_error": None, "customer": None}


def create_transaction(amount, currency, description, callback_url, subscription_id=None) -> dict:
    t = {"id": new_transaction_id(), "type": "payment", "amount": amount, "currency": currency, "status": "pending",
         "description": description or "", "reference": None, "payment_code": None, "refunded": Decimal(0),
         "refund_of": None, "subscription_id": subscription_id, "callback_url": callback_url}
    transactions[t["id"]] = t
    return t


def text(v):
    return None if v is None else (v if isinstance(v, str) else json.dumps(v))


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def send(self, status: int, body, content_type="application/json"):
        data = (to_json(body) if content_type == "application/json" else body).encode()
        self.send_response(status)
        self.send_header("Content-Type", content_type + "; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def fail(self, status: int, error: str, message: str | None = None):
        body = {"success": False, "error": error}
        if message:
            body["message"] = message
        self.send(status, body)

    def body(self):
        length = int(self.headers.get("Content-Length") or 0)
        raw = self.rfile.read(length) if length else b""
        if not raw:
            return None
        try:
            return json.loads(raw)
        except ValueError:
            return None

    def do_GET(self):
        self.route("GET")

    def do_POST(self):
        self.route("POST")

    def route(self, method: str):
        url = urlparse(self.path)
        path = url.path
        if method == "POST" and (m := re.fullmatch(r"/_mock/pay/(tx_[A-Za-z0-9]+)", path)):
            with lock:
                t = transactions.get(m[1])
                if t:
                    t["status"], t["reference"] = "completed", f"HB20261103MOCK{new_id()}"
                    for sid in t.get("subscription_ids") or ([t["subscription_id"]] if t["subscription_id"] else []):
                        s = subscriptions[sid]
                        s["status"], s["started_at"] = "active", datetime.now(timezone.utc) - timedelta(seconds=5)
            return self.send(200 if t else 404, {"success": bool(t)})
        if not path.startswith("/api/v1/"):
            return self.send(404, "Not found", "text/plain")

        auth = self.headers.get("Authorization", "")
        token = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
        if not token:
            return self.send(401, "API key is missing", "text/plain")
        if token != API_KEY:
            return self.send(403, "Invalid API key", "text/plain")

        route = path[len("/api/v1/"):]
        with lock:
            if method == "GET" and route in ("currency/convert", "currency/rate"):
                return self.currency(route, {k: v[0] for k, v in parse_qs(url.query).items()})
            if method == "GET" and route == "subscriptions":
                items = sorted(subscriptions.values(), key=lambda s: -s["seq"])[:100]
                return self.send(200, {"success": True, "subscriptions": [subscription_json(s) for s in items]})
            if method == "GET" and (m := re.fullmatch(r"subscriptions/(sub_[A-Za-z0-9]+)", route)):
                s = subscriptions.get(m[1])
                return self.send(200, {"success": True, "subscription": subscription_json(s)}) if s \
                    else self.fail(404, "subscription_not_found")
            if method != "POST":
                return self.send(405, "", "text/plain")

            body = self.body()
            if m := re.fullmatch(r"subscriptions/([A-Za-z0-9_]+)/(checkout|cancel)", route):
                return self.subscription_action(m[1], m[2], body if isinstance(body, dict) else {})
            if not isinstance(body, dict):
                return self.fail(400, "invalid_request")
            handler = {"payment/request": self.payment_request, "payment/code": self.payment_code,
                       "payment/details": self.payment_details, "payment/refund": self.refund,
                       "subscriptions": self.offer, "subscriptions/checkout": self.offer}.get(route)
            if handler is None:
                return self.send(404, "Not found", "text/plain")
            return handler(body) if handler != self.offer else self.offer(body, checkout=route.endswith("checkout"))

    def payment_request(self, body):
        if "amount" not in body or "currency" not in body:
            return self.fail(400, "missing_parameters")
        amount = number(body["amount"])
        if amount is None or amount <= 0:
            return self.fail(400, "invalid_amount")
        currency = body["currency"] if isinstance(body["currency"], str) else None
        if currency not in DECIMALS:
            return self.fail(400, "unknown_currency")
        amount = round_to(amount, currency)
        if amount <= 0:
            return self.fail(400, "invalid_amount")
        t = create_transaction(amount, currency, text(body.get("description")), text(body.get("callback_url")))
        self.send(200, {"success": True, "transaction_id": t["id"]})

    def transaction_id(self, body):
        raw = body.get("transaction_id")
        if raw is None:
            return None
        # Ids are strings; anything else (a number from before, say) names no payment here.
        return raw if isinstance(raw, str) else ""

    def payment_code(self, body):
        tid = self.transaction_id(body)
        if tid is None:
            return self.fail(400, "missing_parameters")
        t = transactions.get(tid)
        if not t or t["status"] != "pending":
            return self.fail(404, "transaction_not_payable")
        t["payment_code"] = t["payment_code"] or ("mockcode" + t["id"][-8:])
        url = f"{BASE}/p/{t['payment_code']}"
        self.send(200, {"success": True, "code": t["payment_code"], "url": url, "qr_svg": url + "/qr.svg"})

    def payment_details(self, body):
        tid = self.transaction_id(body)
        if tid is None:
            return self.fail(400, "missing_parameters")
        t = transactions.get(tid)
        if not t:
            return self.fail(404, "transaction_not_found")
        self.send(200, {"success": True, "transaction": details(t)})

    def refund(self, body):
        tid = self.transaction_id(body)
        if tid is None:
            return self.fail(400, "missing_parameters")
        amount = None
        if body.get("amount") is not None:
            amount = number(body["amount"])
            if amount is None:
                return self.fail(400, "invalid_amount")
        t = transactions.get(tid)
        if not t:
            return self.fail(404, "transaction_not_found", "Payment not found.")
        left = t["amount"] - t["refunded"]
        if t["status"] != "completed" or t["type"] != "payment" or left <= 0:
            return self.fail(409, "not_refundable", "This payment can't be refunded.")
        amount = left if amount is None else amount
        if amount <= 0 or amount != round_to(amount, t["currency"]):
            return self.fail(400, "invalid_amount", "Enter an amount above 0.")
        if amount > left:
            return self.fail(400, "amount_too_high", "That's more than what can still be refunded.")
        reason = text(body.get("reason"))
        if reason and len(reason) > 200:
            return self.fail(400, "invalid_reason", "The reason can be at most 200 characters.")
        t["refunded"] += amount
        r = {"id": new_transaction_id(), "type": "refund", "amount": amount, "currency": t["currency"], "status": "completed",
             "description": reason or "", "reference": f"HB20261103RF{new_id()}", "payment_code": None,
             "refunded": Decimal(0), "refund_of": t["id"], "subscription_id": None}
        transactions[r["id"]] = r
        self.send(200, {"success": True, "refund": {"id": r["id"], "amount": amount, "currency": r["currency"],
                                                    "reference": r["reference"], "reason": reason},
                        "transaction": details(t)})

    def offer(self, body, checkout: bool):
        if checkout and body.get("subscriptions") is not None:
            return self.checkout_many(body)
        problem = self.offer_problem(body)
        if problem:
            return self.fail(400, *problem)
        s = self.new_offer(body)
        if checkout:
            return self.subscription_action(s["id"], "checkout", body)
        self.send(200, {"success": True, "subscription": subscription_json(s)})

    def checkout_many(self, body):
        """Several subscriptions in one checkout: offer ids or new offers, one currency, all or nothing."""
        items = body["subscriptions"]
        if not isinstance(items, list):
            return self.fail(400, "invalid_subscriptions", "subscriptions has to be a list.")
        if not 1 <= len(items) <= 20:
            return self.fail(400, "invalid_subscriptions", "List 1 to 20 subscriptions.")
        ids = [i if isinstance(i, str) else text(i.get("id")) for i in items if isinstance(i, str) or (isinstance(i, dict) and "id" in i)]
        if len(ids) != len(set(ids)):
            return self.fail(400, "duplicate_subscription", "Each subscription can be listed only once.")
        chosen = []
        for n, item in enumerate(items, 1):
            sid = item if isinstance(item, str) else (text(item.get("id")) if isinstance(item, dict) and "id" in item else None)
            if sid is not None:
                s = subscriptions.get(sid)
                if not s:
                    return self.fail(404, "subscription_not_found", f"Subscription {n}: not found.")
                if s["status"] != "offered":
                    return self.fail(409, "not_open", f"Subscription {n}: it can't be started (anymore).")
                chosen.append(s)
                continue
            problem = self.offer_problem(item if isinstance(item, dict) else None)
            if problem:
                return self.fail(400, problem[0], f"Subscription {n}: {problem[1] if len(problem) > 1 else problem[0]}")
            chosen.append(item)
        if len({(c["currency"] if "seq" in c else text(c["currency"])) for c in chosen}) > 1:
            return self.fail(400, "mixed_currencies", "All subscriptions in one checkout have to be in the same currency.")
        # Validated: only now are the new offers made.
        started = [c if "seq" in c else self.new_offer(c) for c in chosen]
        description = text(body.get("description")) or ", ".join(s["description"] or "Subscription" for s in started)
        t = create_transaction(sum(s["amount"] for s in started), started[0]["currency"], description[:200],
                               text(body.get("callback_url")))
        t["subscription_ids"] = [s["id"] for s in started]
        self.send(200, {"success": True, "transaction_id": t["id"], "subscriptions": [subscription_json(s) for s in started]})

    def offer_problem(self, body):
        """(error, message) for a new offer's fields, or None when they're fine."""
        if not isinstance(body, dict):
            return ("invalid_request",)
        if "amount" not in body or "currency" not in body or "interval" not in body:
            return ("missing_parameters",)
        amount = number(body["amount"])
        if amount is None:
            return ("invalid_amount",)
        count = body.get("interval_count")
        count = Decimal(1) if count is None else number(count)
        if count is None or count != count.to_integral() or not 1 <= count <= 120:
            return ("invalid_interval", "Charge every 1 to 120 days, weeks, months or years.")
        currency = text(body["currency"])
        if currency not in DECIMALS:
            return ("unknown_currency", "Unknown currency.")
        if amount <= 0 or amount != round_to(amount, currency):
            return ("invalid_amount", "Enter an amount above 0.")
        if text(body["interval"]) not in INTERVALS:
            return ("invalid_interval", "Charge every 1 to 120 days, weeks, months or years.")
        description = text(body.get("description"))
        if description and len(description) > 200:
            return ("invalid_description", "The description can be at most 200 characters.")
        return None

    def new_offer(self, body) -> dict:
        currency = text(body["currency"])
        count = body.get("interval_count")
        sid = new_subscription_id()
        s = {"id": sid, "seq": new_id(), "code": "mocksub" + sid[-9:], "status": "offered",
             "amount": round_to(number(body["amount"]), currency), "currency": currency,
             "interval": body["interval"], "interval_count": 1 if count is None else int(number(count)),
             "description": text(body.get("description")), "started_at": None, "canceled_at": None, "canceled_by": None}
        subscriptions[sid] = s
        return s

    def subscription_action(self, sid: str, action: str, body: dict):
        s = subscriptions.get(sid)
        if not s:
            return self.fail(404, "subscription_not_found")
        if action == "cancel":
            if s["canceled_at"]:
                return self.fail(409, "already_canceled")
            s["canceled_at"], s["canceled_by"] = datetime.now(timezone.utc), "merchant"
            s["status"] = "canceled"
            return self.send(200, {"success": True, "subscription": subscription_json(s)})
        if s["status"] != "offered":
            return self.fail(409, "not_open", "This subscription can't be started (anymore). Ask for a new link.")
        t = create_transaction(s["amount"], s["currency"], s["description"], text(body.get("callback_url")), sid)
        self.send(200, {"success": True, "transaction_id": t["id"], "subscription": subscription_json(s)})

    def currency(self, route: str, p: dict):
        body = self.body()
        if body is not None:
            if not isinstance(body, dict):
                return self.fail(400, "invalid_request")
            p = body
        needed = ("currency_from", "currency_to") + (("amount",) if route.endswith("convert") else ())
        if any(k not in p for k in needed):
            return self.fail(400, "missing_parameters")
        if route.endswith("convert") and number(p["amount"]) is None:
            return self.fail(400, "invalid_amount")
        f, t = text(p["currency_from"]), text(p["currency_to"])
        if f not in RATES or t not in RATES:
            return self.fail(400, "unknown_currency")
        rate = RATES[t] / RATES[f]
        if route.endswith("convert"):
            return self.send(200, {"success": True, "amount": round_to(number(p["amount"]) * rate, t)})
        self.send(200, {"success": True, "from_rate": RATES[f] / RATES[t], "to_rate": rate})


def to_json(body) -> str:
    """JSON with Decimals written as exact numbers (24.90 stays 24.90), as .NET writes decimals."""
    marked = json.dumps(body, default=lambda d: f"@@DEC:{d}@@")
    return re.sub(r'"@@DEC:([^@]+)@@"', lambda m: m[1], marked)


def main():
    global BASE
    parser = argparse.ArgumentParser()
    parser.add_argument("--port", type=int, default=8765)
    args = parser.parse_args()
    BASE = f"http://127.0.0.1:{args.port}"
    server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
    print(f"Mock HBank API on {BASE}/api/v1 (API key: {API_KEY})", flush=True)
    server.serve_forever()


if __name__ == "__main__":
    main()
