"""GitStatusWidget - Git repository status display.

Contract: CNT-TUI-WDG-003
Traceability: UX-001, UI-002
"""

from pathlib import Path

from textual.reactive import reactive
from textual.widgets import Static

from laida_cli.tui.services.git_service import GitService, GitStatus


class GitStatusWidget(Static):
    """Widget displaying Git repository status.

    Shows:
    - Current branch name
    - Clean/dirty status
    - Number of changed files
    - Ahead/behind upstream
    """

    DEFAULT_CSS = """
    GitStatusWidget {
        border: round #8b5cf6;
        padding: 1 2;
        margin: 0 1 1 1;
        height: auto;
    }
    """

    # Reactive attributes
    branch: reactive[str] = reactive("--")
    is_clean: reactive[bool] = reactive(True)
    changed_files: reactive[int] = reactive(0)
    sync_status: reactive[str] = reactive("--")
    is_available: reactive[bool] = reactive(True)

    def __init__(
        self,
        project_path: Path,
        git_service: GitService | None = None,
    ) -> None:
        """Initialize with project path.

        Args:
            project_path: Path to the project
            git_service: Git service (creates default if None)
        """
        super().__init__()
        self._project_path = project_path
        self._git_service = git_service or GitService()
        self._last_status: GitStatus | None = None

    def on_mount(self) -> None:
        """Start periodic updates when widget is mounted."""
        # Update every 5 seconds
        self.set_interval(5.0, self._refresh_status)
        # Initial update
        self._refresh_status()

    def _refresh_status(self) -> None:
        """Fetch latest Git status and update reactive attributes."""
        status = self._git_service.get_status(self._project_path)
        self._last_status = status

        if status is None:
            self.is_available = False
            self.branch = "N/A"
            self.is_clean = True
            self.changed_files = 0
            self.sync_status = "--"
        else:
            self.is_available = True
            self.branch = status.branch
            self.is_clean = status.is_clean
            self.changed_files = status.changed_files
            self.sync_status = status.sync_status

    def render(self) -> str:
        """Render the Git status panel content."""
        if not self.is_available:
            return (
                "[bold #a78bfa]🔀 GIT STATUS[/]\n\n"
                "[#64748b]Not a Git repository[/]"
            )

        # Status indicator
        if self.is_clean:
            status_icon = "[#10b981]✔[/]"
            status_text = "[#10b981]Clean[/]"
        else:
            status_icon = "[#fbbf24]●[/]"
            status_text = f"[#fbbf24]{self.changed_files} changed[/]"

        # Branch with sync status
        branch_line = f"[#5eead4]{self.branch}[/]"
        if self.sync_status != "synced":
            branch_line += f" [#64748b]{self.sync_status}[/]"

        return (
            f"[bold #a78bfa]🔀 GIT STATUS[/]\n\n"
            f"Branch: {branch_line}\n"
            f"Status: {status_icon} {status_text}"
        )

    @property
    def git_status(self) -> GitStatus | None:
        """Get the last Git status."""
        return self._last_status
