"""Cursor adapter — GUI-based tool, no subprocess wrapping."""

from __future__ import annotations

from datetime import datetime, timezone
from typing import TYPE_CHECKING

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

if TYPE_CHECKING:
    from nestdx.policy.watcher import FileWatcher


class CursorAdapter(ToolAdapter):
    """Adapter for the Cursor IDE.

    Cursor is a GUI editor — there is no CLI subprocess to wrap.
    Instead, ``run()`` prints instructions and blocks until the user
    signals they are done (Enter or Ctrl+C).

    When a :class:`FileWatcher` is provided, it is started before blocking
    and stopped after the user signals completion.
    """

    def __init__(self, watcher: FileWatcher | None = None):
        self._watcher = watcher

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

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

    def validate(self) -> bool:
        # GUI app — nothing to check on PATH.
        return True

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

        if self._watcher and not self._watcher.is_running:
            self._watcher.start()

        print(
            "\n"
            "Cursor session active.\n"
            "Use Cursor normally. When you're done, press Enter or Ctrl+C.\n"
        )

        try:
            input("Press Enter to end the session...")
        except (KeyboardInterrupt, EOFError):
            pass

        if self._watcher and self._watcher.is_running:
            self._watcher.stop()

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