"""
Tests for kodara.ci.generator and the `kodara init-ci` CLI command.
"""
from __future__ import annotations

from pathlib import Path

import pytest
import yaml
from click.testing import CliRunner

from kodara.ci.generator import WORKFLOW_CONTENT, generate_workflow, workflow_exists
from kodara.cli.main import main


# ── generate_workflow ──────────────────────────────────────────────────────────

class TestGenerateWorkflow:

    def test_creates_file_at_correct_path(self, tmp_path):
        result = generate_workflow(tmp_path)
        expected = tmp_path / ".github" / "workflows" / "kodara.yml"
        assert result == expected
        assert result.exists()

    def test_creates_workflows_dir_if_missing(self, tmp_path):
        assert not (tmp_path / ".github").exists()
        generate_workflow(tmp_path)
        assert (tmp_path / ".github" / "workflows").is_dir()

    def test_file_contains_ci_check(self, tmp_path):
        path = generate_workflow(tmp_path)
        assert "kodara ci-check" in path.read_text(encoding="utf-8")

    def test_file_contains_checkout_action(self, tmp_path):
        path = generate_workflow(tmp_path)
        assert "actions/checkout" in path.read_text(encoding="utf-8")

    def test_raises_file_exists_error_if_already_present(self, tmp_path):
        generate_workflow(tmp_path)
        with pytest.raises(FileExistsError):
            generate_workflow(tmp_path)


# ── workflow_exists ────────────────────────────────────────────────────────────

class TestWorkflowExists:

    def test_returns_false_when_missing(self, tmp_path):
        assert workflow_exists(tmp_path) is False

    def test_returns_true_when_present(self, tmp_path):
        generate_workflow(tmp_path)
        assert workflow_exists(tmp_path) is True


# ── WORKFLOW_CONTENT ──────────────────────────────────────────────────────────

class TestWorkflowContent:

    def test_is_valid_yaml(self):
        parsed = yaml.safe_load(WORKFLOW_CONTENT)
        assert isinstance(parsed, dict)
        assert "jobs" in parsed


# ── CLI init-ci ────────────────────────────────────────────────────────────────

class TestInitCiCommand:

    def test_creates_file_in_tmp_path(self, tmp_path):
        runner = CliRunner()
        result = runner.invoke(main, ["init-ci", str(tmp_path)])
        assert result.exit_code == 0
        assert (tmp_path / ".github" / "workflows" / "kodara.yml").exists()
        assert "CI workflow created" in result.output

    def test_force_overwrites_existing_file(self, tmp_path):
        # Create initial file
        generate_workflow(tmp_path)
        original_target = tmp_path / ".github" / "workflows" / "kodara.yml"
        original_content = original_target.read_text(encoding="utf-8")

        runner = CliRunner()
        result = runner.invoke(main, ["init-ci", str(tmp_path), "--force"])
        assert result.exit_code == 0
        assert original_target.exists()
        assert "CI workflow created" in result.output
        # File should contain the canonical workflow content
        assert "kodara ci-check" in original_target.read_text(encoding="utf-8")

    def test_no_force_with_existing_file_shows_message(self, tmp_path):
        generate_workflow(tmp_path)

        runner = CliRunner()
        result = runner.invoke(main, ["init-ci", str(tmp_path)])
        assert result.exit_code == 0
        assert "already exists" in result.output
        assert "--force" in result.output

    def test_no_force_with_existing_file_does_not_overwrite(self, tmp_path):
        generate_workflow(tmp_path)
        target = tmp_path / ".github" / "workflows" / "kodara.yml"
        target.write_text("custom content", encoding="utf-8")

        runner = CliRunner()
        runner.invoke(main, ["init-ci", str(tmp_path)])
        # File should still contain custom content (not overwritten)
        assert target.read_text(encoding="utf-8") == "custom content"


# ── Regression: existing imports still work ───────────────────────────────────

class TestRegressionImports:

    def test_existing_imports_work(self):
        from kodara.memory.store import MemoryStore
        from kodara.indexer.scanner import RepositoryScanner
        from kodara.engine_client import query_context, query_impact
        from kodara.graph.dependency import DependencyGraph
        assert MemoryStore is not None
        assert RepositoryScanner is not None
        assert query_context is not None
        assert query_impact is not None
        assert DependencyGraph is not None
