"""
Same JSON as the product page → POST /api/order (session auth via test client).

Requires at least one user in smilehub.db. Temporarily credits wallet for the test.

  set GAME_ID / SERVER_ID (or defaults below)
  python tools/webapp_ph_mlbb_cheapest_order.py
"""
from __future__ import annotations

import json
import os
import sys
import time
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
os.chdir(ROOT)

try:
    from dotenv import load_dotenv

    load_dotenv(ROOT / ".env")
except ImportError:
    pass

import models
from app import app


def _first_user_id() -> int:
    conn = models.get_db()
    row = conn.execute("SELECT id FROM users ORDER BY id ASC LIMIT 1").fetchone()
    conn.close()
    if not row:
        print("No users in smilehub.db — register once at /register, then re-run.", file=sys.stderr)
        sys.exit(1)
    return int(row["id"])


def main() -> None:
    game_id = (os.environ.get("GAME_ID") or "962293364").strip()
    zone_id = (os.environ.get("SERVER_ID") or os.environ.get("ZONE_ID") or "6463").strip()

    uid = _first_user_id()
    models.adjust_balance(uid, 5_000_000)

    from config import DEFAULT_MARKUP_PCT
    from currency import parse_php_amount_from_text, php_amount_to_mmk_str
    from scraper_playwright import run_game_packages_cached

    url = "https://www.smile.one/ph/merchant/mobilelegends"
    data = run_game_packages_cached(url, bypass_cache=True)
    rows = data.get("packages") or []

    best_row = None
    best_cents: int | None = None
    for p in rows:
        pt = (p.get("price_text") or "").strip()
        amt = parse_php_amount_from_text(pt)
        if amt is None:
            continue
        c = int((amt * Decimal(100)).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
        if c <= 0:
            continue
        if best_cents is None or c < best_cents:
            best_cents = c
            best_row = p

    if not best_row or best_cents is None:
        print("No PHP package found.", file=sys.stderr)
        sys.exit(1)

    name = (best_row.get("name") or "").strip()
    li = str((best_row.get("smile_li_id") or "")).strip()
    php_amt = Decimal(best_cents) / Decimal(100)
    _, mmk_dec, _ = php_amount_to_mmk_str(php_amt, DEFAULT_MARKUP_PCT)
    mmk_int = int(mmk_dec)

    payload = {
        "url": url,
        "package_brl_cents": None,
        "package_php_cents": best_cents,
        "package_name": name,
        "package_index": None,
        "mmk_price": mmk_int,
        "product_name": ((data.get("title") or "") or "Mobile Legends")[:200],
        "smile_li_id": li or None,
        "form_data": {"game_id": game_id, "server_id": zone_id},
    }

    print("[webapp-test] user_id=", uid, "cheapest php_cents=", best_cents, "mmk_price=", mmk_int, "li=", li)
    print("[webapp-test] POST /api/order …")

    with app.test_client() as client:
        with client.session_transaction() as sess:
            sess["user_id"] = uid

        r = client.post("/api/order", json=payload)
        print("HTTP", r.status_code)
        body = r.get_json()
        print(json.dumps(body, indent=2, ensure_ascii=False))

        if r.status_code != 200 or not body or not body.get("ok"):
            sys.exit(1)
        if body.get("status") != "running":
            sys.exit(0)

        oid = body.get("order_id")
        for i in range(120):
            time.sleep(2)
            r2 = client.get(f"/api/order-status?order_id={oid}")
            st = r2.get_json()
            if not st:
                continue
            s = st.get("status")
            print(f"[webapp-test] poll {i + 1}: status={s}")
            if s == "done":
                print(json.dumps(st, indent=2, ensure_ascii=False))
                sys.exit(0 if st.get("ok") else 2)
            if s == "idle" and i > 3:
                print(json.dumps(st, indent=2, ensure_ascii=False))
                break

        print("Timed out waiting for order completion.", file=sys.stderr)
        sys.exit(3)


if __name__ == "__main__":
    main()
