import json
import os
from pathlib import Path

_IIS_DIR = Path.home() / ".iis"


def get_account_url() -> str:
    if url := os.environ.get("IIS_ACCOUNT_URL"):
        return url.rstrip("/")
    config = _load_config()
    return config.get("accountUrl", "https://account.iis.tools").rstrip("/")


def get_nexus_url() -> str:
    if url := os.environ.get("IIS_NEXUS_URL"):
        return url.rstrip("/")
    config = _load_config()
    return config.get("nexusUrl", "http://localhost:9666").rstrip("/")


def is_auth_disabled() -> bool:
    return os.environ.get("IIS_NO_AUTH") == "1"


def get_credentials() -> dict | None:
    path = _IIS_DIR / "credentials.json"
    if not path.exists():
        return None
    try:
        with open(path) as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError):
        return None


def _load_config() -> dict:
    path = _IIS_DIR / "config.json"
    if not path.exists():
        return {}
    try:
        with open(path) as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError):
        return {}
