"""Tests for launcher.skills.init_cmd module."""

from __future__ import annotations

from pathlib import Path
from unittest.mock import patch


class TestRunInit:
    """Test project initialization."""

    def test_creates_directories(self, tmp_path: Path, monkeypatch, capsys):
        monkeypatch.chdir(tmp_path)
        from launcher.skills.init_cmd import run_init

        run_init(project_dir=tmp_path)

        assert (tmp_path / ".claude" / "rules").is_dir()
        assert (tmp_path / ".claude" / "skills").is_dir()
        assert (tmp_path / ".claude" / "rules" / "project.md").is_file()

    def test_generates_project_md(self, tmp_path: Path, monkeypatch, capsys):
        monkeypatch.chdir(tmp_path)
        # Create a package.json so detection works
        (tmp_path / "package.json").write_text('{"name": "test-app"}')

        from launcher.skills.init_cmd import run_init

        run_init(project_dir=tmp_path)

        content = (tmp_path / ".claude" / "rules" / "project.md").read_text()
        assert "test-app" in content

    def test_skips_if_project_md_exists(self, tmp_path: Path, monkeypatch, capsys):
        monkeypatch.chdir(tmp_path)
        rules_dir = tmp_path / ".claude" / "rules"
        rules_dir.mkdir(parents=True)
        (rules_dir / "project.md").write_text("existing content")

        from launcher.skills.init_cmd import run_init

        run_init(project_dir=tmp_path)

        captured = capsys.readouterr()
        assert "already exists" in captured.out
        # Content should not be overwritten
        assert (rules_dir / "project.md").read_text() == "existing content"

    def test_prints_detected_info(self, tmp_path: Path, monkeypatch, capsys):
        monkeypatch.chdir(tmp_path)
        (tmp_path / "package.json").write_text('{"name": "my-app", "dependencies": {"react": "^18"}}')
        (tmp_path / "tsconfig.json").write_text("{}")

        from launcher.skills.init_cmd import run_init

        run_init(project_dir=tmp_path)

        captured = capsys.readouterr()
        assert "TypeScript" in captured.out
        assert "React" in captured.out

    def test_handles_mkdir_oserror_gracefully(self, tmp_path: Path, monkeypatch, capsys):
        """OSError on mkdir should print a message to stderr, not crash with NameError."""
        monkeypatch.chdir(tmp_path)

        from launcher.skills.init_cmd import run_init

        with patch("launcher.skills.init_cmd.Path.mkdir", side_effect=OSError("permission denied")):
            run_init(project_dir=tmp_path)

        captured = capsys.readouterr()
        assert "permission denied" in captured.err
