"""SDK-backed profile loading helpers."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Any

import typer

from worai.config import resolve_config_path

try:
    from wordlift_sdk.kg_build import load_profile_config
except ModuleNotFoundError:  # pragma: no cover - environment dependent
    load_profile_config = None


def resolve_profile_name(ctx: typer.Context | None, explicit_profile: str | None = None) -> str:
    if explicit_profile:
        return explicit_profile
    if ctx and ctx.obj and ctx.obj.get("profile"):
        return str(ctx.obj["profile"])
    return os.environ.get("WORAI_PROFILE", "default")


def resolve_profile_config_path(ctx: typer.Context | None) -> Path:
    if ctx and ctx.obj and ctx.obj.get("config_path"):
        return Path(ctx.obj["config_path"]).resolve()
    return resolve_config_path(None)


def load_profile(ctx: typer.Context | None, explicit_profile: str | None = None) -> tuple[Any, str, Path]:
    if load_profile_config is None:
        raise ValueError("wordlift-sdk kg_build support is unavailable in this Python environment")

    profile_name = resolve_profile_name(ctx, explicit_profile)
    config_path = resolve_profile_config_path(ctx)
    try:
        config = load_profile_config(config_path)
    except Exception as exc:
        raise ValueError(f"Failed loading profile config from {config_path}: {exc}") from exc

    profile = config.get(profile_name)
    if profile is None:
        raise ValueError(f"Profile '{profile_name}' not found in {config_path}")
    return profile, profile_name, config_path


def load_raw_profile(ctx: typer.Context | None) -> dict[str, Any]:
    """Return the full raw profile dict from TOML, including custom/nested sections.

    Unlike ``load_profile`` (which uses the SDK loader and drops unknown keys),
    this reads the TOML file directly so that sections like ``[profiles.x.gsheets]``
    are preserved.
    """
    import tomllib

    config_path = resolve_profile_config_path(ctx)
    try:
        with config_path.open("rb") as fh:
            data = tomllib.load(fh)
    except (FileNotFoundError, OSError):
        return {}
    profile_name = resolve_profile_name(ctx)
    profiles: dict = data.get("profiles") or data.get("profile") or {}
    return dict(profiles.get(profile_name) or {})


def resolve_profile_api_key(
    ctx: typer.Context | None,
    explicit_profile: str | None = None,
) -> tuple[str | None, str, Path]:
    profile, profile_name, config_path = load_profile(ctx, explicit_profile)
    api_key = getattr(profile, "api_key", None) or os.environ.get("WORDLIFT_API_KEY")
    return api_key, profile_name, config_path
