"""Shared helpers for agentic CLI command modules."""

from __future__ import annotations

import json
import os
from typing import Any

import click

from centris_sdk.client import Centris

DEFAULT_API_KEY = "ck_test_local_development"
DEFAULT_API_URL = "http://127.0.0.1:18789"


def get_api_key(ctx: click.Context, key_override: str | None = None) -> str:
    """Resolve API key from CLI override, env var, or active profile config."""
    if key_override:
        return key_override

    env_key = os.environ.get("CENTRIS_API_KEY")
    if env_key:
        return env_key

    deps = ctx.obj.get("deps") if ctx.obj else None
    if deps:
        config_key = deps.config_loader.get("CENTRIS_API_KEY")
        if config_key:
            return config_key

    # Keep local-first behavior for development flows.
    return DEFAULT_API_KEY


def get_api_url(ctx: click.Context) -> str:
    """Resolve API base URL from env var, active profile config, or local default."""
    env_url = os.environ.get("CENTRIS_API_URL")
    if env_url:
        return env_url

    deps = ctx.obj.get("deps") if ctx.obj else None
    if deps:
        config_url = deps.config_loader.get("CENTRIS_API_URL")
        if config_url:
            return config_url

    return DEFAULT_API_URL


def create_api_client(
    ctx: click.Context,
    key: str | None,
    base_url: str | None,
    timeout: int,
) -> Centris:
    """Build a configured SDK client for Action API-backed CLI commands."""
    return Centris(
        api_key=get_api_key(ctx, key),
        base_url=base_url or get_api_url(ctx),
        timeout=float(timeout),
    )


def parse_json_object(raw: str | None, label: str) -> dict[str, Any]:
    """Parse a JSON object argument and raise a user-facing Click error on failure."""
    if not raw:
        return {}
    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise click.ClickException(f"{label} must be valid JSON: {exc}") from exc
    if not isinstance(parsed, dict):
        raise click.ClickException(f"{label} must be a JSON object")
    return parsed
