import subprocess
from pathlib import Path

import pytest
from typer import Exit

from mitch.errors import MissingMigrationError, NoProjectFound
from mitch.project import Project
from mitch.vcs import GitManager


def _run_git(cwd, *args):
    result = subprocess.run(
        ["git", *args],
        cwd=cwd,
        capture_output=True,
        text=True,
        check=False,
    )
    assert result.returncode == 0, result.stderr or result.stdout
    return result.stdout.strip()


def _init_git_repo(path):
    _run_git(path, "init")


def _write_project_config(path: Path, project_id: str = "tests-project") -> None:
    (path / "mitch.toml").write_text(f'[project]\nid = "{project_id}"\n', encoding="utf-8")


def test_load_project():
    project = Project.from_path(Path("tests/migrations"))

    migration = project.by_id("001-init")
    assert migration is not None

    assert migration.id == "001-init"
    assert migration.up_script.name == "001-init.up.sql"
    assert migration.down_script is None
    assert migration.config_file is None
    assert migration.transactional is True
    assert migration.idempotent is False
    assert migration.dependencies == set()


def test_load_project_with_dependencies():
    project = Project.from_path(Path("tests/migrations"))
    migrations = list(project.by_ids_with_dependencies(["002-add-column"]))
    assert migrations[0].id == "001-init"
    assert migrations[1].id == "002-add-column"


def test_load_project_with_dependants():
    project = Project.from_path(Path("tests/migrations"))
    migrations = list(project.by_ids_with_dependants(["001-init"]))
    assert migrations[0].id == "002-add-column"
    assert migrations[1].id == "001-init"


def test_sort_by_created_at_then_id(tmp_path):
    _write_project_config(tmp_path, "sort-test")
    (tmp_path / "001-init.up.sql").write_text("SELECT 1;", encoding="utf-8")
    (tmp_path / "002-second.up.sql").write_text("SELECT 1;", encoding="utf-8")

    (tmp_path / "003-old.up.sql").write_text("SELECT 1;", encoding="utf-8")
    (tmp_path / "003-old.config.toml").write_text("created_at = 2020-01-01\n", encoding="utf-8")

    (tmp_path / "004-new.up.sql").write_text("SELECT 1;", encoding="utf-8")
    (tmp_path / "004-new.config.toml").write_text("created_at = 2020-01-02\n", encoding="utf-8")

    project = Project.from_path(tmp_path)
    migrations = list(project.by_ids_with_dependencies(["001-init", "002-second", "003-old", "004-new"]))

    assert [m.id for m in migrations] == ["003-old", "004-new", "001-init", "002-second"]


def test_by_paths_raises_if_any_path_is_missing():
    project = Project.from_path(Path("tests/migrations"))

    with pytest.raises(MissingMigrationError):
        list(
            project.by_paths(
                [
                    "tests/migrations/001-init.up.sql",
                    "tests/migrations/does-not-exist.up.sql",
                ]
            )
        )


def test_get_migration_manager_finds_git_in_parent_directory(tmp_path):
    project_root = tmp_path / "project"
    project_root.mkdir()
    _write_project_config(project_root, "git-parent")
    _init_git_repo(project_root)

    migrations_path = project_root / "migrations"
    migrations_path.mkdir()
    (migrations_path / "001-init.up.sql").write_text("SELECT 1;", encoding="utf-8")

    project = Project.from_path(migrations_path)

    manager = project.get_migration_manager()

    assert isinstance(manager, GitManager)


def test_get_migration_manager_raises_when_no_repository_metadata(tmp_path):
    _write_project_config(tmp_path, "no-vcs")
    project = Project.from_path(tmp_path)

    with pytest.raises(Exit):
        project.get_migration_manager()


def test_from_path_finds_project_root_in_parent_directory(tmp_path):
    _write_project_config(tmp_path, "parent-root")
    nested = tmp_path / "nested" / "deeper"
    nested.mkdir(parents=True)

    project = Project.from_path(nested)

    assert project.path == tmp_path.resolve()
    assert project.id == "parent-root"


def test_from_path_raises_when_config_is_missing(tmp_path):
    with pytest.raises(NoProjectFound):
        Project.from_path(tmp_path)


def test_project_config_requires_project_id(tmp_path):
    (tmp_path / "mitch.toml").write_text("[project]\n", encoding="utf-8")

    with pytest.raises(ValueError):
        Project.from_path(tmp_path)
