"""Generic adapter — wraps arbitrary CLI commands."""

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 GenericAdapter(ToolAdapter):
    """Adapter for arbitrary commands via ``nestdx run -- <command>``."""

    def __init__(self, command: list[str]):
        if not command:
            raise ValueError("Command must not be empty.")
        self._command = command

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

    def resolve_command(self, config: ToolConfig) -> list[str]:
        return list(self._command)

    def validate(self) -> bool:
        return shutil.which(self._command[0]) is not None

    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,
        )
