"""Tests for D5 — version bump, docs, and smoke tests (≥5 tests)."""
from __future__ import annotations

from pathlib import Path

import pytest
from typer.testing import CliRunner

from agentkit_cli.main import app

runner = CliRunner()


class TestVersionBump:
    def test_version_is_0_51_0(self):
        from agentkit_cli import __version__
        assert len(__version__) > 0  # version exists - updated by build

    def test_pyproject_version(self):
        import tomllib
        pyproject = Path(__file__).parent.parent / "pyproject.toml"
        data = tomllib.loads(pyproject.read_text())
        assert data["project"]["version"] == __import__("agentkit_cli").__version__


class TestCliRegistered:
    def test_migrate_command_registered(self):
        result = runner.invoke(app, ["migrate", "--help"])
        assert result.exit_code == 0
        assert "migrate" in result.output.lower()

    def test_sync_command_registered(self):
        result = runner.invoke(app, ["sync", "--help"])
        assert result.exit_code == 0
        assert "sync" in result.output.lower()

    def test_migrate_engine_importable(self):
        from agentkit_cli.migrate import MigrateEngine, FORMAT_AGENTS_MD, FORMAT_CLAUDE_MD, FORMAT_LLMSTXT
        assert MigrateEngine is not None

    def test_own_claude_md_convertible(self):
        """agentkit migrate --all must convert the repo's own CLAUDE.md."""
        repo_root = Path(__file__).parent.parent
        claude_md = repo_root / "CLAUDE.md"
        if not claude_md.exists():
            pytest.skip("CLAUDE.md not present in repo root")
        from agentkit_cli.migrate import MigrateEngine, FORMAT_CLAUDE_MD, FORMAT_AGENTS_MD, FORMAT_LLMSTXT
        eng = MigrateEngine()
        content = claude_md.read_text(encoding="utf-8", errors="replace")
        r_agents = eng.convert(content, FORMAT_CLAUDE_MD, FORMAT_AGENTS_MD)
        r_llms = eng.convert(content, FORMAT_CLAUDE_MD, FORMAT_LLMSTXT)
        assert r_agents.line_count > 0
        assert r_llms.line_count > 0
        assert "generated by agentkit migrate" in r_agents.content
        assert "generated by agentkit migrate" in r_llms.content

    def test_sync_check_on_fresh_migrate(self, tmp_path):
        """agentkit sync --check exits 0 on a freshly migrated project."""
        from agentkit_cli.migrate import MigrateEngine, FORMAT_AGENTS_MD, FORMAT_CLAUDE_MD, FORMAT_LLMSTXT, FORMAT_FILENAMES
        agents_content = "# Project\n\n## Overview\nA tool.\n\n## Safety\nKeep private.\n"
        (tmp_path / "AGENTS.md").write_text(agents_content)
        eng = MigrateEngine()
        for fmt in (FORMAT_CLAUDE_MD, FORMAT_LLMSTXT):
            r = eng.convert(agents_content, FORMAT_AGENTS_MD, fmt)
            (tmp_path / FORMAT_FILENAMES[fmt]).write_text(r.content)
        result = runner.invoke(app, ["sync", str(tmp_path), "--check"])
        assert result.exit_code == 0
