"""Gemini API 키 라운드로빈 풀.

GEMINI_API_KEY(기본) + GEMINI_API_KEY1, GEMINI_API_KEY2, ... 순서로 수집.
호출마다 다음 키를 반환하여 rate limit 분산.

키 소스: os.environ → .env 파일 (pydantic settings가 로드하는 것과 동일)
"""

import logging
import os
import threading
from pathlib import Path

logger = logging.getLogger(__name__)

_keys: list[str] = []
_counter: int = 0
_lock = threading.Lock()
_initialized = False


def _load_dotenv_keys() -> dict[str, str]:
    """pydantic이 로드하는 .env 파일에서 GEMINI_API_KEY* 값 수집."""
    # backend/.env (gemini_key_pool.py → llm/ → modules/ → app/ → backend/)
    env_file = Path(__file__).resolve().parent.parent.parent.parent / ".env"
    if not env_file.exists():
        return {}
    result = {}
    for line in env_file.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "=" not in line:
            continue
        key, _, val = line.partition("=")
        key = key.strip()
        val = val.strip().strip('"').strip("'")
        if key.startswith("GEMINI_API_KEY"):
            result[key] = val
    return result


def _init() -> None:
    global _keys, _initialized
    if _initialized:
        return
    with _lock:
        if _initialized:
            return

        # .env 파일과 os.environ 모두에서 키 수집 (os.environ 우선)
        dotenv = _load_dotenv_keys()
        all_sources = {**dotenv, **dict(os.environ)}

        # 기본 키 (GEMINI_API_KEY)
        base_key = all_sources.get("GEMINI_API_KEY", "")
        if base_key:
            _keys.append(base_key)

        # 추가 키 (GEMINI_API_KEY1, GEMINI_API_KEY2, ...)
        i = 1
        while True:
            k = all_sources.get(f"GEMINI_API_KEY{i}", "")
            if not k:
                break
            if k not in _keys:  # 중복 방지
                _keys.append(k)
            i += 1

        _initialized = True
        logger.info("Gemini key pool: %d key(s) loaded", len(_keys))


def get_next_key() -> str:
    """라운드로빈으로 다음 API 키 반환."""
    global _counter
    _init()
    if not _keys:
        raise RuntimeError("No Gemini API keys configured")
    if len(_keys) == 1:
        return _keys[0]
    with _lock:
        idx = _counter % len(_keys)
        _counter += 1
        return _keys[idx]


def key_count() -> int:
    _init()
    return len(_keys)
