"""
verify_frontend.py — เปิดหน้าเว็บจริงด้วยเบราว์เซอร์ แล้วตรวจว่า:
  1) ข้อความเตือน INVALID_FORMAT แสดงช่วงหมวดตามที่ Backend ตอบมา (ไม่ใช่ 70-85 ที่เขียนตายตัว)
  2) ช่องพิมพ์มือถูกล้างเมื่อเริ่มสแกนคันใหม่ (ไม่ค้างเลขของคันก่อน)
  3) placeholder ของช่องพิมพ์มืออัปเดตตามช่วงหมวดจริง
รัน: python verify_frontend.py
"""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

FRONTEND = Path(__file__).resolve().parent / "frontend" / "index.html"
PLATE_RANGE = "50-99"


class Stub(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def _json(self, obj):
        body = json.dumps(obj).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path.startswith("/api/health"):
            return self._json({
                "status": "ok", "warnings": [],
                "ai": {"ready": True, "detector_kind": "plate"},
                "database": {"ok": True},
                "plate_range": PLATE_RANGE,
            })
        body = FRONTEND.read_bytes()
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        # จำลองกรณีป้ายที่หมวดไม่อยู่ในช่วง — เส้นทางเดียวกับที่หน้างานเจอ
        self._json({"success": False, "code": "INVALID_FORMAT",
                    "message": "รูปแบบไม่ตรง", "plate": None})


srv = HTTPServer(("127.0.0.1", 8799), Stub)
threading.Thread(target=srv.serve_forever, daemon=True).start()

from playwright.sync_api import sync_playwright  # noqa: E402

FAILED = []


def check(label, got, want):
    ok = got == want
    print(f"  [{'OK' if ok else 'FAIL'}]   {label}\n         ได้: {got!r}")
    if not ok:
        FAILED.append(f"{label} (ได้ {got!r} ต้องการ {want!r})")


with sync_playwright() as p:
    b = p.chromium.launch(executable_path="/opt/pw-browsers/chromium")
    pg = b.new_page()
    errors = []
    pg.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
    pg.goto("http://127.0.0.1:8799/", wait_until="networkidle")
    pg.wait_for_timeout(600)

    check("ไม่มี console error ตอนโหลดหน้า", errors, [])
    check("placeholder อัปเดตตามช่วงหมวดจริง",
          "หมวด 50-99" in pg.input_value.__self__.locator("#plateInput").get_attribute("placeholder"),
          True)

    # จำลองว่ามีเลขของ "รถคันก่อน" ค้างอยู่ในช่อง แล้วสแกนคันใหม่
    pg.fill("#plateInput", "71-2953")
    pg.set_input_files("#cameraInput", {
        "name": "t.jpg", "mimeType": "image/jpeg",
        # JPEG ขนาดเล็กสุดที่ decode ได้จริง
        "buffer": bytes.fromhex(
            "ffd8ffe000104a46494600010100000100010000ffdb004300ffffffffffffffff"
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc200"
            "0b080001000101011100ffc40014000100000000000000000000000000000009ff"
            "da0008010100003f00d2cf20ffd9")
    })
    pg.wait_for_timeout(2500)

    check("ช่องพิมพ์มือถูกล้าง ไม่ค้างเลขคันก่อน", pg.input_value("#plateInput"), "")
    status = pg.text_content("#status") or ""
    check("ข้อความเตือนใช้ช่วงหมวดจากเซิร์ฟเวอร์", "หมวด 50-99" in status, True)
    check("ไม่มีเลข 70-85 ที่เขียนตายตัวโผล่มาอีก", "70-85" in status, False)
    print(f"\n  สถานะที่แสดงจริง: {status.strip()[:110]}")
    b.close()

srv.shutdown()
print("\n" + "=" * 54)
print("ผ่านทั้งหมด" if not FAILED else "ล้มเหลว:\n  - " + "\n  - ".join(FAILED))
print("=" * 54)
raise SystemExit(1 if FAILED else 0)
