"""Project init step - detects project stack and creates project.md."""

from __future__ import annotations

import subprocess
from pathlib import Path

from installer.context import InstallContext
from installer.steps.base import BaseStep


def _find_tribunal_binary() -> Path | None:
    """Find the tribunal binary in ~/.tribunal/bin/."""
    binary = Path.home() / ".tribunal" / "bin" / "tribunal"
    if binary.exists() and binary.stat().st_mode & 0o111:
        return binary
    return None


class ProjectInitStep(BaseStep):
    """Step that initializes .claude/rules/project.md via tribunal skills init."""

    name = "project_init"

    def check(self, ctx: InstallContext) -> bool:
        """Skip if project.md already exists."""
        return (ctx.project_dir / ".claude" / "rules" / "project.md").exists()

    def run(self, ctx: InstallContext) -> None:
        """Run tribunal skills init to detect project and create project.md."""
        ui = ctx.ui

        binary = _find_tribunal_binary()
        if not binary:
            if ui:
                ui.info("Tribunal binary not available, skipping project init")
            return

        if ui:
            ui.status("Detecting project stack...")

        try:
            result = subprocess.run(
                [str(binary), "skills", "init"],
                capture_output=True,
                text=True,
                timeout=15,
                cwd=str(ctx.project_dir),
            )
        except (subprocess.TimeoutExpired, OSError) as exc:
            if ui:
                ui.warning(f"Project init failed: {exc}")
            return

        if result.returncode == 0:
            if ui:
                ui.success("Project detected and project.md created")
        else:
            if ui:
                ui.info("Could not auto-detect project (run 'tribunal skills init' manually)")
