"""Codex CLI adapter — invokes codex via subprocess."""

from __future__ import annotations

import logging
import subprocess
from dataclasses import dataclass, field
from typing import Any

from dpe.adapters.base import ModelAdapter
from dpe.models.adapter import ModelRequest, ModelResult

logger = logging.getLogger(__name__)


@dataclass
class CodexCliAdapter(ModelAdapter):
    """Adapter that calls the Codex CLI tool."""

    command_template: str = "codex -q {prompt_file}"
    timeout_seconds: int = 120
    _call_count: int = field(default=0, init=False)

    def generate(self, request: ModelRequest) -> ModelResult:
        import tempfile
        from pathlib import Path

        self._call_count += 1

        with tempfile.NamedTemporaryFile(
            mode="w", suffix=".txt", delete=False, encoding="utf-8"
        ) as f:
            f.write(request.prompt)
            prompt_file = f.name

        try:
            cmd = self.command_template.replace("{prompt_file}", prompt_file)
            cmd_parts = cmd.split()

            logger.info("CodexCli: executing %s", cmd_parts[0])
            result = subprocess.run(
                cmd_parts,
                capture_output=True,
                text=True,
                timeout=self.timeout_seconds,
            )

            throttle_detected = result.returncode != 0 and (
                "rate" in result.stderr.lower() or "throttl" in result.stderr.lower()
            )

            if result.returncode != 0 and not throttle_detected:
                logger.error("CodexCli error: %s", result.stderr[:500])
                return ModelResult(
                    text=f"[ERROR] {result.stderr[:1000]}",
                    adapter_name="codex_cli",
                    role=request.role,
                    throttle_detected=False,
                    metadata={"returncode": result.returncode},
                )

            return ModelResult(
                text=result.stdout,
                adapter_name="codex_cli",
                role=request.role,
                throttle_detected=throttle_detected,
                metadata={"returncode": result.returncode},
            )
        except subprocess.TimeoutExpired:
            logger.error("CodexCli: timeout after %ds", self.timeout_seconds)
            return ModelResult(
                text="[ERROR] Timeout",
                adapter_name="codex_cli",
                role=request.role,
                throttle_detected=True,
                metadata={"timeout": True},
            )
        finally:
            Path(prompt_file).unlink(missing_ok=True)

    def healthcheck(self) -> bool:
        try:
            result = subprocess.run(
                ["codex", "--version"],
                capture_output=True,
                text=True,
                timeout=10,
            )
            return result.returncode == 0
        except (subprocess.TimeoutExpired, FileNotFoundError):
            return False

    def estimate_usage(self, request: ModelRequest) -> dict[str, Any]:
        return {"estimated_tokens": len(request.prompt) // 4}

    def get_usage_snapshot(self) -> dict[str, Any]:
        return {"total_calls": self._call_count}
