"""Shared profile/env/CLI resolution helpers for command modules."""

from __future__ import annotations

import os
from typing import Any

import typer

from worai.core.profile_loader import load_profile, resolve_profile_name


def load_profile_settings(ctx: typer.Context | None) -> tuple[dict[str, Any], str]:
    safe_ctx = ctx if hasattr(ctx, "obj") else None
    try:
        profile, profile_name, _ = load_profile(safe_ctx)
    except ValueError:
        return {}, resolve_profile_name(safe_ctx)
    settings = getattr(profile, "settings", {}) or {}
    return settings, profile_name


def resolve_value(
    value: Any,
    profile_settings: dict[str, Any],
    *,
    paths: list[str] | None = None,
    env_keys: list[str] | None = None,
) -> Any:
    if value is not None and value != "":
        return value
    for env_key in env_keys or []:
        if env_key in os.environ:
            return os.environ[env_key]
    for path in paths or []:
        underscore_key = path.replace(".", "_")
        if underscore_key in profile_settings:
            return profile_settings[underscore_key]
        if path in profile_settings:
            return profile_settings[path]
    return None


def resolve_token_path(
    token_value: str | None,
    profile_settings: dict[str, Any],
) -> str:
    return str(
        resolve_value(
            token_value,
            profile_settings,
            paths=["oauth.token", "gsc.token", "ga.token"],
            env_keys=["OAUTH_TOKEN", "GSC_TOKEN", "GA_TOKEN"],
        )
        or "oauth_token.json"
    )


def resolve_oauth_client_secrets(
    client_secrets_value: str | None,
    profile_settings: dict[str, Any],
) -> str | None:
    return resolve_value(
        client_secrets_value,
        profile_settings,
        paths=["oauth.client_secrets"],
        env_keys=["GSC_CLIENT_SECRETS"],
    )


def resolve_gsc_site_id(
    site_value: str | None,
    profile_settings: dict[str, Any],
) -> str | None:
    return resolve_value(
        site_value,
        profile_settings,
        paths=["gsc_site_id", "gsc.id"],
        env_keys=["GSC_ID"],
    )


def resolve_ga_property_id(
    ga_value: str | None,
    profile_settings: dict[str, Any],
) -> str | None:
    return resolve_value(
        ga_value,
        profile_settings,
        paths=["ga_property_id", "ga.id"],
        env_keys=["GA_ID"],
    )
