"""Adapter layer -- convert framework-specific reward setups to NormalizedEnvironment."""

from __future__ import annotations

import ast
from pathlib import Path
from typing import Optional

from rewardprobe.adapters.base import BaseAdapter
from rewardprobe.adapters.raw import RawAdapter
from rewardprobe.adapters.trl import TRLAdapter
from rewardprobe.adapters.verifiers import VerifiersAdapter

__all__ = [
    "BaseAdapter",
    "RawAdapter",
    "TRLAdapter",
    "VerifiersAdapter",
    "detect_adapter",
]


def _file_has_load_environment(file_path: str) -> bool:
    """Check whether a Python file defines a ``load_environment()`` function.

    Uses AST parsing so we never need to import the file (which might pull in
    heavy dependencies).
    """
    try:
        source = Path(file_path).read_text()
        tree = ast.parse(source)
    except (OSError, SyntaxError):
        return False

    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == "load_environment":
            return True
    return False


def detect_adapter(
    file_path: Optional[str] = None,
    adapter_hint: Optional[str] = None,
) -> type[BaseAdapter]:
    """Return the appropriate adapter class for the given inputs.

    Parameters
    ----------
    file_path:
        Path to an environment/reward file.  If the file contains a
        ``load_environment()`` function it is treated as a verifiers env.
    adapter_hint:
        Explicit adapter override (e.g. ``"trl"``, ``"raw"``,
        ``"verifiers"``).  Takes precedence over auto-detection.

    Returns
    -------
    type[BaseAdapter]
        The adapter **class** (not an instance).
    """
    # Explicit override
    if adapter_hint is not None:
        hint = adapter_hint.lower().strip()
        if hint == "trl":
            return TRLAdapter
        if hint in ("verifiers", "verifier"):
            return VerifiersAdapter
        if hint == "raw":
            return RawAdapter
        raise ValueError(f"Unknown adapter hint: {adapter_hint!r}")

    # Auto-detect from file contents
    if file_path is not None and _file_has_load_environment(file_path):
        return VerifiersAdapter

    # Default fallback
    return RawAdapter
