#!/usr/bin/env python3
"""Validate Baidu OAuth credentials without exposing them in argv or output."""

import argparse
import json
import re
import urllib.parse
import urllib.request
from pathlib import Path


def load_env(path: Path) -> dict[str, str]:
    values = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        if not line or line.startswith("#"):
            continue
        key, sep, value = line.partition("=")
        if not sep or not re.fullmatch(r"[A-Z][A-Z0-9_]*", key):
            raise ValueError("invalid secret env")
        values[key] = value
    return values


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--secrets-env", type=Path, required=True)
    args = parser.parse_args()
    values = load_env(args.secrets_env)
    body = urllib.parse.urlencode(
        {
            "grant_type": "client_credentials",
            "client_id": values["BAIDU_FACE_API_KEY"],
            "client_secret": values["BAIDU_FACE_SECRET_KEY"],
        }
    ).encode()
    request = urllib.request.Request(
        "https://aip.baidubce.com/oauth/2.0/token",
        data=body,
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=15) as response:
        result = json.loads(response.read().decode("utf-8"))
    if not result.get("access_token"):
        raise ValueError("Baidu OAuth response did not contain access_token")
    print("BAIDU_CREDENTIAL_PASS")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

