"""Configura ADC de Google a partir de Settings / .env."""

from __future__ import annotations

import logging
import os
from pathlib import Path

from config import Settings, get_settings

logger = logging.getLogger(__name__)


def configure_google_credentials(settings: Settings | None = None) -> Path | None:
    """
    Si hay GOOGLE_CREDENTIAL (ruta al JSON de service account), exporta
    GOOGLE_APPLICATION_CREDENTIALS para los clientes de Speech/TTS.
    """
    cfg = settings or get_settings()
    raw = (cfg.google_credential or "").strip().strip("'\"")
    if not raw:
        existing = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", "").strip()
        if existing and Path(existing).is_file():
            return Path(existing)
        return None

    path = Path(raw)
    if not path.is_absolute():
        backend_dir = Path(__file__).resolve().parent.parent
        candidates = [
            backend_dir / raw,
            backend_dir.parent / raw,
            Path.cwd() / raw,
        ]
        for candidate in candidates:
            if candidate.is_file():
                path = candidate
                break

    if not path.is_file():
        logger.warning(
            "GOOGLE_CREDENTIAL no encontrado: %s (ADC de Google no configurado)",
            raw,
        )
        return None

    resolved = str(path.resolve())
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = resolved
    if cfg.google_project_id:
        os.environ.setdefault("GOOGLE_CLOUD_PROJECT", cfg.google_project_id.strip().strip("'\""))
    logger.info("Google ADC: %s", resolved)
    return path.resolve()
