"""Environment loading helpers for pipeline LLM/API keys.

Policy:
- Load project-local env files for CLI/web commands.
- Do not overwrite keys that are already exported in the shell.
- Canonical Gemini key variable is GOOGLE_API_KEY.
- DEFAULT_OPTIMIZER_MODEL is used by proposer + trajectory summarizer (not the agent).
"""

from __future__ import annotations

import os
from pathlib import Path

from clawbench._paths import _PROJECT_ROOT

# Default model for optimizer LLM calls (proposer + trajectory summarizer).
# The agent model is separate and controlled by CLI --model.
DEFAULT_OPTIMIZER_MODEL = "gemini/gemini-3.1-flash-lite-preview"

# Score threshold for PASS/FAIL classification.
# Used consistently across eval display, JSON artifacts, and dashboard data.
PASS_THRESHOLD = 0.8


def load_local_env_files(project_root: Path | None = None) -> list[Path]:
    """Load local env files into os.environ without overriding existing keys.

    Files are loaded in this order:
    1) <repo>/.gemini/.env
    2) <repo>/.env
    """
    root = project_root or _PROJECT_ROOT
    candidates = [
        root / ".gemini" / ".env",
        root / ".env",
    ]
    loaded: list[Path] = []

    for env_path in candidates:
        if not env_path.exists() or not env_path.is_file():
            continue
        for line in env_path.read_text().splitlines():
            parsed = _parse_env_line(line)
            if parsed is None:
                continue
            key, value = parsed
            if key not in os.environ:
                os.environ[key] = value
        loaded.append(env_path)

    # Alias: gemini-cli uses GEMINI_API_KEY; pipeline uses GOOGLE_API_KEY
    gemini_key = os.environ.get("GEMINI_API_KEY")
    if gemini_key and "GOOGLE_API_KEY" not in os.environ:
        os.environ["GOOGLE_API_KEY"] = gemini_key

    return loaded


def _parse_env_line(line: str) -> tuple[str, str] | None:
    line = line.strip()
    if not line or line.startswith("#"):
        return None
    if line.startswith("export "):
        line = line[len("export ") :].strip()
    if "=" not in line:
        return None
    key, value = line.split("=", 1)
    key = key.strip()
    value = value.strip().strip('"').strip("'")
    if not key:
        return None
    return key, value

