#!/usr/bin/env python3
"""Log in to choke77i.com and save the returned auth token locally."""

import json
import os
import stat
import tempfile
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


API_URL = "https://player-api.c77api.com/v1/auth/login"
OUTPUT_FILE = Path(__file__).with_name("choke_token.txt")
SITE_URL = "https://choke77i.com"
USERNAME = "appa1"
PASSWORD = "12345678"


def main() -> None:
    payload = json.dumps(
        {"username": USERNAME, "password": PASSWORD, "rememberMe": True}
    ).encode("utf-8")
    request = Request(
        API_URL,
        data=payload,
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Origin": SITE_URL,
            "Referer": f"{SITE_URL}/login",
            "User-Agent": (
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/140.0.0.0 Safari/537.36"
            ),
        },
        method="POST",
    )

    try:
        with urlopen(request, timeout=20) as response:
            result = json.load(response)
    except HTTPError as exc:
        raise SystemExit(f"เข้าสู่ระบบไม่สำเร็จ: HTTP {exc.code}") from exc
    except URLError as exc:
        raise SystemExit(f"เชื่อมต่อ API ไม่สำเร็จ: {exc.reason}") from exc

    token = result.get("token")
    if not isinstance(token, str) or not token:
        raise SystemExit("การตอบกลับไม่มี token")

    # Write atomically and restrict the file to the current user.
    OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary_name = tempfile.mkstemp(
        prefix=f".{OUTPUT_FILE.name}.", dir=OUTPUT_FILE.parent, text=True
    )
    try:
        # Allow PHP (www-data) to read the token, but deny other users.
        os.fchmod(fd, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP)
        try:
            www_data_gid = __import__("grp").getgrnam("www-data").gr_gid
            os.fchown(fd, -1, www_data_gid)
        except KeyError:
            pass
        with os.fdopen(fd, "w", encoding="utf-8") as file:
            file.write(token + "\n")
        os.replace(temporary_name, OUTPUT_FILE)
    except Exception:
        try:
            os.unlink(temporary_name)
        except FileNotFoundError:
            pass
        raise

    print(f"บันทึก token แล้ว: {OUTPUT_FILE}")


if __name__ == "__main__":
    main()
