# Copyright (c) Metis. All rights reserved.

"""Shared HTTP client with centralized auth and config for the mantis CLI.

Credential priority:
1. CLI flags (--host, --api-key)
2. Environment variables (INSIGHT_HOST, INSIGHT_SECRET_KEY)
3. Config file (~/.mantis/config.json)
4. Error with helpful message
"""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path
from typing import Any, Dict, Optional, Tuple

CONFIG_DIR = Path.home() / ".mantis"
CONFIG_FILE = CONFIG_DIR / "config.json"


def get_config() -> Dict[str, Any]:
    """Read config from ~/.mantis/config.json."""
    if not CONFIG_FILE.exists():
        return {}
    return json.loads(CONFIG_FILE.read_text())


def save_config(config: Dict[str, Any]) -> None:
    """Write config to ~/.mantis/config.json."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
    CONFIG_FILE.write_text(json.dumps(config, indent=2))
    CONFIG_FILE.chmod(0o600)


def get_credentials(
    host: Optional[str] = None,
    api_key: Optional[str] = None,
    public_key: Optional[str] = None,
) -> Tuple[str, str, str]:
    """Resolve host, public_key, and secret_key from flags, env vars, or config.

    Args:
        host: Explicit host override (from CLI flag).
        api_key: Explicit secret key override (from CLI flag).
        public_key: Explicit public key override (from CLI flag).

    Returns:
        Tuple of (host, public_key, secret_key).

    Raises:
        SystemExit: If credentials cannot be resolved.
    """
    config = get_config()

    resolved_host = host or os.getenv("INSIGHT_HOST") or config.get("host")
    resolved_secret = api_key or os.getenv("INSIGHT_SECRET_KEY") or config.get("api_key")
    resolved_public = public_key or os.getenv("INSIGHT_PUBLIC_KEY") or config.get("public_key")

    if not resolved_host:
        print(
            "Error: Host not configured. Use --host, set INSIGHT_HOST, " "or run `mantis auth login`.",
            file=sys.stderr,
        )
        sys.exit(1)

    if not resolved_secret:
        print(
            "Error: Secret key not configured. Use --api-key, set INSIGHT_SECRET_KEY, " "or run `mantis auth login`.",
            file=sys.stderr,
        )
        sys.exit(1)

    if not resolved_public:
        print(
            "Error: Public key not configured. Use --public-key, set INSIGHT_PUBLIC_KEY, "
            "or run `mantis auth login`.",
            file=sys.stderr,
        )
        sys.exit(1)

    return resolved_host, resolved_public, resolved_secret


def create_client(
    host: Optional[str] = None,
    api_key: Optional[str] = None,
) -> Any:
    """Create an httpx.Client with Basic auth.

    Args:
        host: Explicit host override.
        api_key: Explicit api_key override.

    Returns:
        httpx.Client configured with base_url and auth.
    """
    try:
        import httpx
    except ImportError:
        print(
            "httpx is required. Install with: pip install mantisdk[platform]",
            file=sys.stderr,
        )
        sys.exit(1)

    resolved_host, resolved_public, resolved_secret = get_credentials(host, api_key)

    return httpx.Client(
        base_url=resolved_host.rstrip("/"),
        auth=(resolved_public, resolved_secret),
        timeout=30.0,
    )
