"""Interactive setup run on the hosting server, outside the public web root."""
import getpass
import json
import os
from pathlib import Path
import secrets
from urllib.parse import urlsplit

from reporting import numeric_id


def main():
    target = Path(__file__).with_name("private-config.json")
    if target.exists():
        raise SystemExit("A config already exists. Edit it securely on the server; setup will not overwrite it.")
    print("Paw Barn Reporting — private pilot setup\nNo credentials are sent to ChatGPT.")
    origin = input("Dedicated HTTPS origin (e.g. https://reporting.example.com): ").strip().rstrip("/")
    parsed = urlsplit(origin)
    if parsed.scheme != "https" or not parsed.hostname or parsed.path or parsed.query or parsed.fragment or parsed.username:
        raise SystemExit("Use a dedicated HTTPS origin, without a path or login details.")
    account = numeric_id(input("Lightspeed R-Series Account ID (not a Shop ID): ").strip())
    print("Register a private Lightspeed OAuth client with this redirect URI:")
    print(origin + "/auth/callback")
    client_id = getpass.getpass("Lightspeed client ID (hidden): ").strip()
    client_secret = getpass.getpass("Lightspeed client secret (hidden): ").strip()
    if not client_id or not client_secret:
        raise SystemExit("Client ID and secret are required.")
    config = {"public_url": origin, "account_id": account,
              "client_id": client_id, "client_secret": client_secret,
              "signing_key": secrets.token_urlsafe(48), "cursor_key": secrets.token_urlsafe(48),
              "state_dir": str(Path(__file__).with_name("private-state").resolve()),
              "chatgpt_redirect_uris": ["https://chatgpt.com/connector_platform_oauth_redirect"]}
    fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "w") as handle:
        json.dump(config, handle, indent=2)
        handle.write("\n")
    print("Private configuration saved. Keep it outside public_html and out of backups shared with others.")
    print("After adding the MCP server, compare ChatGPT's displayed redirect URI with the config allowlist.")


if __name__ == "__main__":
    main()
