#!/usr/bin/env python3
"""Create task-local DM8 credentials in a Git-ignored, owner-only file."""

import json
import os
import secrets
import string
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
TARGET = ROOT / "config/local/dm8-smart-canteen-compat-20260928.json"
ALPHABET = string.ascii_letters + string.digits + "@#_"


def password() -> str:
    required = [
        secrets.choice(string.ascii_uppercase),
        secrets.choice(string.ascii_lowercase),
        secrets.choice(string.digits),
        secrets.choice("@#_"),
    ]
    required.extend(secrets.choice(ALPHABET) for _ in range(20))
    secrets.SystemRandom().shuffle(required)
    return "".join(required)


def main() -> None:
    if TARGET.exists():
        raise SystemExit("Private credential file already exists; refusing to replace it")
    values = {
        "ZHCT_COMPAT": {
            "port": 5237,
            "sysdba_password": password(),
            "sysauditor_password": password(),
            "app_user": "ZHCT_APP",
            "app_password": password(),
        },
        "AIZHCT_COMPAT": {
            "port": 5238,
            "sysdba_password": password(),
            "sysauditor_password": password(),
            "app_user": "AIZHCT_APP",
            "app_password": password(),
        },
    }
    TARGET.parent.mkdir(parents=True, exist_ok=True)
    fd = os.open(TARGET, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(values, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
    print(f"Created private credential file: {TARGET}; content withheld")


if __name__ == "__main__":
    main()
