#!/usr/bin/env python3
"""檢查關卡卡 JSON 是否齊全，並加總預估秒數。"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

REQUIRED = ("id", "hook", "conflict", "player_choice", "payoff", "estimated_seconds")


def validate(path: Path, budget: int) -> int:
    data = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(data, list) or not data:
        print("檔案必須是非空的關卡卡陣列。", file=sys.stderr)
        return 1
    errors = 0
    total = 0
    seen_ids: set[str] = set()
    for index, card in enumerate(data, start=1):
        missing = [key for key in REQUIRED if key not in card or card[key] in ("", None)]
        if missing:
            print(f"第 {index} 張缺少欄位：{', '.join(missing)}")
            errors += 1
            continue
        if card["id"] in seen_ids:
            print(f"重複的編號：{card['id']}")
            errors += 1
        seen_ids.add(card["id"])
        try:
            seconds = int(card["estimated_seconds"])
        except (TypeError, ValueError):
            print(f"{card['id']} 的 estimated_seconds 不是整數")
            errors += 1
            continue
        if seconds <= 0:
            print(f"{card['id']} 的秒數必須大於 0")
            errors += 1
        total += seconds
        print(f"OK  {card['id']} 約 {seconds} 秒：{card['hook'][:24]}…")
    print(f"合計預估 {total} 秒（預算 {budget} 秒）")
    if total > budget:
        print("已超過預算，請刪減或拆關。")
        errors += 1
    return 1 if errors else 0


def main() -> int:
    parser = argparse.ArgumentParser(description="檢查遊戲關卡卡")
    parser.add_argument("file", type=Path)
    parser.add_argument("--budget", type=int, default=300, help="預估秒數上限，預設 300")
    args = parser.parse_args()
    return validate(args.file, args.budget)


if __name__ == "__main__":
    sys.exit(main())
