import sqlite3
import subprocess

import pytest
from typer.testing import CliRunner

from mitch.cli import app

runner = CliRunner()


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


def _has_hg() -> bool:
    result = subprocess.run(
        ["hg", "--version"],
        capture_output=True,
        text=True,
        check=False,
    )
    return result.returncode == 0


pytestmark = pytest.mark.skipif(not _has_hg(), reason="Mercurial (hg) is not available")


def _run_hg(cwd, *args):
    result = subprocess.run(
        ["hg", *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_hg_repo(path):
    _run_hg(path, "init")


def test_checkout_hg_reverts_migrations_missing_on_target_branch(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_hg_repo(repo_path)

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_hg(repo_path, "add", ".")
    _run_hg(repo_path, "commit", "-m", "add 001", "-u", "test")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_hg(repo_path, "branch", "target")
    _run_hg(repo_path, "rm", "001-init.up.sql", "001-init.down.sql")
    _run_hg(repo_path, "commit", "-m", "remove migration", "-u", "test")
    _run_hg(repo_path, "update", "default")

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0

    branch = _run_hg(repo_path, "branch")
    assert branch == "target"

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute("SELECT id FROM mitch_migrations").fetchall()
        table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_one'",
        ).fetchone()

    assert rows == []
    assert table is None


def _write_linked_layout(root, users):
    _write_project_config(root, "app")
    (root / "groups.up.sql").write_text("CREATE TABLE groups (id int);", encoding="utf-8")
    (root / "groups.down.sql").write_text("DROP TABLE groups;", encoding="utf-8")
    (root / "groups.config.toml").write_text('dependencies = ["users:create-users"]\n', encoding="utf-8")
    users.mkdir(exist_ok=True)
    _write_project_config(users, "org.example.users")
    (users / "create-users.up.sql").write_text("CREATE TABLE users (id int);", encoding="utf-8")
    (users / "create-users.down.sql").write_text("DROP TABLE users;", encoding="utf-8")


def test_checkout_hg_warns_when_nested_linked_project_differs_on_target(tmp_path):
    root = tmp_path / "app"
    root.mkdir()
    _write_linked_layout(root, root / "users")
    _init_hg_repo(root)
    _run_hg(root, "add", ".")
    _run_hg(root, "commit", "-m", "base", "-u", "test")
    database_url = f"sqlite:///{tmp_path / 'test.db'}"
    assert runner.invoke(app, ["up", "-p", str(root), "-d", database_url]).exit_code == 0

    (root / "users" / "create-users.up.sql").write_text("CREATE TABLE users (id int, name text);", encoding="utf-8")
    _run_hg(root, "commit", "-m", "change linked", "-u", "test")
    _run_hg(root, "update", "0")

    result = runner.invoke(app, ["checkout", "1", "-p", str(root), "-d", database_url])

    assert result.exit_code == 0, result.output
    assert "Warning" in result.output and "users" in result.output


def test_checkout_hg_warns_when_subrepository_of_linked_project_moves(tmp_path):
    root = tmp_path / "app"
    root.mkdir()
    _init_hg_repo(root)
    users = root / "users"
    users.mkdir()
    _init_hg_repo(users)
    _write_linked_layout(root, users)
    _run_hg(users, "add", ".")
    _run_hg(users, "commit", "-m", "v1", "-u", "test")
    (root / ".hgsub").write_text("users = users\n", encoding="utf-8")
    _run_hg(root, "add", ".hgsub", "groups.up.sql", "groups.down.sql", "groups.config.toml", "mitch.toml")
    _run_hg(root, "commit", "-m", "base", "-u", "test")
    database_url = f"sqlite:///{tmp_path / 'test.db'}"
    assert runner.invoke(app, ["up", "-p", str(root), "-d", database_url]).exit_code == 0

    (users / "audit.up.sql").write_text("CREATE TABLE audit (id int);", encoding="utf-8")
    _run_hg(users, "add", "audit.up.sql")
    _run_hg(users, "commit", "-m", "v2", "-u", "test")
    _run_hg(root, "commit", "-m", "bump users", "-u", "test")
    _run_hg(root, "update", "0")

    result = runner.invoke(app, ["checkout", "1", "-p", str(root), "-d", database_url])

    assert result.exit_code == 0, result.output
    assert "Warning" in result.output and "users" in result.output
