"""
test_camera.py — ทดสอบการอ่านป้ายจาก "กล้องจริง" แทนการอัปโหลดรูปทีละใบ

รองรับ 3 แบบ:
    1) กล้อง IP / CCTV ผ่าน RTSP   : python test_camera.py rtsp://user:pass@192.168.1.50:554/stream1
    2) ไฟล์วิดีโอที่อัดมาจากกล้อง  : python test_camera.py clip.mp4
    3) เว็บแคมที่เสียบกับเครื่อง    : python test_camera.py 0

ทำไมต้องมีไฟล์นี้แยกจาก /api/scan:
    หน้าเว็บบน iPad ส่งมา "ภาพนิ่ง 1 ใบต่อ 1 คัน" แต่กล้องวงจรปิดส่งมาเป็นสตรีมต่อเนื่อง
    ซึ่งต่างกันที่การจัดการ 3 เรื่อง และนั่นคือสิ่งที่สคริปต์นี้ทดสอบ:
      - ต้องเลือกเฟรมมาอ่าน ไม่ใช่อ่านทุกเฟรม (อ่านทุกเฟรมเครื่องไม่ไหวแน่นอน)
      - รถคันเดียวโผล่หลายเฟรม ต้องรวมเป็นคันเดียว ไม่ใช่เรียกคิวซ้ำ 30 รอบ
      - แต่หลายเฟรมคือ "ข้อดี" เพราะเอามาโหวตกันได้ แม่นกว่าภาพนิ่งใบเดียว

ผลลัพธ์ที่ได้จะบอก fps จริงที่เครื่องนี้ไหว และเวลาเฉลี่ยต่อเฟรม
ใช้ตัดสินใจได้ว่าเครื่องปัจจุบันพอสำหรับงาน realtime ไหม หรือต้องขยับไป GPU
"""
from __future__ import annotations

import sys
import time
from collections import Counter, deque

import cv2

sys.path.insert(0, ".")
from app import pipeline as pl  # noqa: E402
from app import plate_utils as pu  # noqa: E402

# ---- ค่าที่ปรับได้ ----
SAMPLE_EVERY_SEC = 0.5   # อ่านทุกกี่วินาที (ไม่ใช่ทุกเฟรม) 0.5 = 2 ครั้ง/วินาที
GROUP_GAP_SEC = 4.0      # เงียบไปเกินกี่วินาทีถือว่าเป็น "รถคันใหม่"
MIN_VOTES_STREAM = 2     # ต้องอ่านได้ตรงกันกี่เฟรมจึงประกาศผล
SHOW_WINDOW = False      # True = เปิดหน้าต่างดูภาพด้วย (ต้องมีจอ)


def main(source: str) -> int:
    src = int(source) if source.isdigit() else source
    cap = cv2.VideoCapture(src)
    if not cap.isOpened():
        print(f"[ผิดพลาด] เปิดกล้อง/วิดีโอไม่ได้: {source}")
        print("  - RTSP: ลองเปิดด้วย VLC ก่อนว่า URL ถูกไหม")
        print("  - ไฟล์วิดีโอ: ตรวจว่าไฟล์อยู่โฟลเดอร์เดียวกับสคริปต์")
        return 1

    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    src_fps = cap.get(cv2.CAP_PROP_FPS) or 0
    print(f"\nเปิดกล้องได้: {w}x{h} @ {src_fps:.0f} fps (ต้นทาง)")
    print("กำลังโหลดโมเดล AI ... (ครั้งแรกใช้เวลาสักพัก)")

    pl.pipeline.load()
    print(f"โมเดลพร้อม: {pl.pipeline.detector_kind}\n")
    print("กด Ctrl+C เพื่อหยุด\n")
    print(f"{'เวลา':>8} | {'ผลที่อ่านได้':<16} | {'มั่นใจ':>6} | {'ใช้เวลา':>8}")
    print("-" * 52)

    votes: Counter = Counter()
    last_seen = 0.0
    announced = None
    times: deque = deque(maxlen=50)
    frames_read = 0
    next_sample = 0.0

    try:
        while True:
            ok, frame = cap.read()
            if not ok:
                break
            frames_read += 1
            now = time.time()

            if SHOW_WINDOW:
                cv2.imshow("camera", frame)
                if cv2.waitKey(1) & 0xFF == 27:
                    break

            if now < next_sample:
                continue
            next_sample = now + SAMPLE_EVERY_SEC

            # รถคันก่อนหายไปนานแล้ว -> เริ่มนับใหม่
            if last_seen and now - last_seen > GROUP_GAP_SEC:
                votes.clear()
                announced = None

            t0 = time.time()
            res = pl.pipeline.scan(frame)
            dt = time.time() - t0
            times.append(dt)

            if res.ok and res.plate:
                last_seen = now
                votes[(res.plate, res.province_abbr)] += 1
                (plate, abbr), n = votes.most_common(1)[0]
                shown = pu.format_plate(plate, abbr)
                if n >= MIN_VOTES_STREAM and shown != announced:
                    announced = shown
                    print(f"{time.strftime('%H:%M:%S'):>8} | {shown:<16} "
                          f"| {res.confidence*100:5.0f}% | {dt:6.2f}s  <-- ยืนยัน {n} เฟรม")
                else:
                    print(f"{time.strftime('%H:%M:%S'):>8} | {shown:<16} "
                          f"| {res.confidence*100:5.0f}% | {dt:6.2f}s  (รอโหวต {n}/{MIN_VOTES_STREAM})")
    except KeyboardInterrupt:
        print("\nหยุดโดยผู้ใช้")
    finally:
        cap.release()
        if SHOW_WINDOW:
            cv2.destroyAllWindows()

    if times:
        avg = sum(times) / len(times)
        print("\n" + "=" * 52)
        print(f"เฟรมที่รับมาทั้งหมด : {frames_read}")
        print(f"เฟรมที่เอาเข้า AI   : {len(times)}")
        print(f"เวลาเฉลี่ยต่อเฟรม   : {avg:.2f} วินาที")
        print(f"ความเร็วที่เครื่องนี้ไหว : {1/avg:.2f} เฟรม/วินาที")
        if avg > 1.0:
            print("\nสรุป: เครื่องนี้ยังไม่ไหวสำหรับ realtime เต็มรูปแบบ")
            print("      ใช้แบบ 'ถ่ายเมื่อมีรถเข้ามา' (trigger) ได้ แต่สตรีมต่อเนื่องต้องใช้ GPU")
        else:
            print("\nสรุป: เครื่องนี้พอไหวสำหรับการอ่านแบบสุ่มเฟรมต่อเนื่อง")
        print("=" * 52)
    return 0


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)
    sys.exit(main(sys.argv[1]))
