"""FileTreeWidget - Project file browser widget.

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

from pathlib import Path

from textual.widgets import Static


class FileTreeWidget(Static):
    """Widget displaying project outputs file tree.

    Shows the outputs/ directory structure with:
    - Phase directories
    - Step directories with status indicators
    - Recently created files highlighted
    """

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

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

        Args:
            project_path: Path to LAIDA project
        """
        super().__init__()
        self._project_path = project_path
        self._outputs_dir = project_path / "outputs"

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

    def _refresh_tree(self) -> None:
        """Refresh the file tree display."""
        # Force re-render
        self.refresh()

    def render(self) -> str:
        """Render the file tree."""
        lines = ["[bold #a78bfa]📂 PROJECT FILES[/]", ""]

        if not self._outputs_dir.exists():
            lines.append("[#64748b]outputs/ (empty)[/]")
            return "\n".join(lines)

        lines.append("[#5eead4]outputs/[/]")

        # Scan phases 0-4
        for phase in range(5):
            phase_dir = self._outputs_dir / f"phase{phase}"
            if not phase_dir.exists():
                lines.append(f"  [#64748b]├─ phase{phase}/ (pending)[/]")
                continue

            # Phase exists, check steps
            lines.append(f"  [#10b981]├─ phase{phase}/[/]")

            for step in range(4):
                step_dirs = list(phase_dir.glob(f"step{step}_*"))
                if step_dirs:
                    step_dir = step_dirs[0]
                    step_name = step_dir.name
                    has_index = (step_dir / "_index.yaml").exists()

                    if has_index:
                        # Completed step
                        lines.append(f"  │   [#10b981]├─ {step_name}/ ✔[/]")
                    else:
                        # In progress
                        lines.append(f"  │   [#fbbf24]├─ {step_name}/ ●[/]")
                else:
                    # Pending step
                    lines.append(f"  │   [#64748b]├─ step{step}_... (pending)[/]")

        return "\n".join(lines)
