"""Utilities for writing and testing zscaler-oneapi.conf.

Shared by scripts/setup.py and the CLI settings menu so both surfaces
produce identical output and apply the same security posture.
"""

import os
import stat
import sys
from pathlib import Path
from typing import Optional

if sys.platform == "win32":
    DEFAULT_CONF_PATH = str(
        Path(os.environ.get("APPDATA", Path.home())) / "zs-config" / "zscaler-oneapi.conf"
    )
else:
    DEFAULT_CONF_PATH = "/etc/zscaler-oneapi.conf"
DEFAULT_ONEAPI_URL = "https://api.zsapi.net"


def build_zidentity_url(subdomain: str) -> str:
    return f"https://{subdomain.strip().lower()}.zslogin.net"


def write_conf(
    path: str,
    vanity_subdomain: str,
    client_id: str,
    client_secret: str,
    zpa_customer_id: Optional[str] = None,
    oneapi_base_url: str = DEFAULT_ONEAPI_URL,
) -> str:
    """Write the conf file and set permissions to 600.

    Returns the resolved absolute path of the written file.
    Raises PermissionError if the path is not writable.
    """
    zidentity_url = build_zidentity_url(vanity_subdomain)

    lines = [
        "# Zscaler OneAPI Configuration",
        "# Generated by zscaler-scripts setup",
        "#",
        "# SECURITY: This file contains sensitive credentials.",
        "# Permissions are set to 600 (owner read/write only).",
        "# Never commit this file to version control.",
        "",
        f'export ZIDENTITY_BASE_URL="{zidentity_url}"',
        f'export ONEAPI_BASE_URL="{oneapi_base_url}"',
        "",
        "# OAuth Client Credentials — shared across all Zscaler products",
        f'export ZSCALER_CLIENT_ID="{client_id}"',
        f'export ZSCALER_CLIENT_SECRET="{client_secret}"',
        "",
        "# ZPA-specific",
    ]

    if zpa_customer_id:
        lines.append(f'export ZPA_CUSTOMER_ID="{zpa_customer_id}"')
    else:
        lines.append('# export ZPA_CUSTOMER_ID=""  # Uncomment and set if using ZPA')

    content = "\n".join(lines) + "\n"

    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(content)
    if sys.platform != "win32":
        os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)  # 600

    return str(p.resolve())


def test_credentials(vanity_subdomain: str, client_id: str, client_secret: str) -> None:
    """Attempt an OAuth token request to verify the credentials are valid.

    Raises on failure — requests.HTTPError for API errors, or ConnectionError
    if the ZIdentity URL is unreachable.
    """
    from lib.auth import ZscalerAuth

    auth = ZscalerAuth(build_zidentity_url(vanity_subdomain), client_id, client_secret)
    auth.get_token()
