"""Codex adapter — interactive subprocess with stdin/stdout passthrough."""

from __future__ import annotations

import shutil
import signal
import subprocess
from datetime import datetime, timezone

from nestdx.adapters.base import ToolAdapter
from nestdx.config.schema import ToolConfig
from nestdx.session.models import ToolRun


class CodexAdapter(ToolAdapter):
    """Adapter for the OpenAI Codex CLI (`codex`)."""

    @property
    def name(self) -> str:
        return "codex"

    def resolve_command(self, config: ToolConfig) -> list[str]:
        cmd = ["codex"]
        model = config.config.get("model")
        if model:
            cmd.extend(["--model", model])
        provider = config.config.get("provider")
        if provider:
            cmd.extend(["--provider", provider])
        return cmd

    def validate(self) -> bool:
        return shutil.which("codex") is not None

    @property
    def install_hint(self) -> str:
        return "Install Codex: npm install -g @openai/codex"

    def run(self, config: ToolConfig, extra_args: list[str]) -> ToolRun:
        cmd = self.resolve_command(config) + extra_args
        start_time = datetime.now(timezone.utc)

        original_sigint = signal.getsignal(signal.SIGINT)
        signal.signal(signal.SIGINT, signal.SIG_IGN)

        try:
            result = subprocess.run(cmd)
            exit_code = result.returncode
        except Exception:
            exit_code = 1
        finally:
            signal.signal(signal.SIGINT, original_sigint)

        return ToolRun(
            tool=self.name,
            command=" ".join(cmd),
            start_time=start_time,
            end_time=datetime.now(timezone.utc),
            exit_code=exit_code,
        )
