"""Rework, rebuild, ordering constraints and the ID-based checkout plan (GitLab issue #2).

All tests drive mitch through the CLI against SQLite files and git repositories under tmp_path.
"""

import sqlite3
import subprocess
from pathlib import Path

from typer.testing import CliRunner

from mitch.cli import app

runner = CliRunner()


def mitch(*args: str):
    return runner.invoke(app, list(args))


def git(cwd: Path, *args: str) -> str:
    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_repo(path: Path) -> str:
    git(path, "init")
    git(path, "config", "user.email", "test@example.com")
    git(path, "config", "user.name", "Test User")
    return path.name


def commit_all(path: Path, message: str) -> None:
    git(path, "add", "-A")
    git(path, "commit", "-m", message)


def write_migration(root: Path, stem: str, up: str, down: str | None = None, config: str | None = None) -> None:
    (root / f"{stem}.up.sql").write_text(up, encoding="utf-8")
    if down is not None:
        (root / f"{stem}.down.sql").write_text(down, encoding="utf-8")
    if config is not None:
        (root / f"{stem}.config.toml").write_text(config, encoding="utf-8")


def new_project(path: Path, project_id: str = "app") -> Path:
    path.mkdir(parents=True, exist_ok=True)
    (path / "mitch.toml").write_text(f'[project]\nid = "{project_id}"\n', encoding="utf-8")
    return path


def db_url(tmp_path: Path) -> str:
    return f"sqlite:///{tmp_path / 'test.db'}"


def audit(tmp_path: Path) -> list[tuple[str, str]]:
    """(migration ID, action) in the order they happened."""
    with sqlite3.connect(tmp_path / "test.db") as connection:
        return connection.execute("SELECT migration_id, action FROM mitch_migration_audit ORDER BY id").fetchall()


def applied_ids(tmp_path: Path) -> set[str]:
    with sqlite3.connect(tmp_path / "test.db") as connection:
        return {row[0] for row in connection.execute("SELECT id FROM mitch_migrations")}


FUNCTION_V1 = "DROP VIEW IF EXISTS answer; CREATE VIEW answer AS SELECT 41 AS value;"
FUNCTION_V2 = "DROP VIEW IF EXISTS answer; CREATE VIEW answer AS SELECT 42 AS value;"


def test_checkout_back_across_a_rework_reverts_only_the_new_version(tmp_path):
    root = new_project(tmp_path / "repo")
    init_repo(root)
    write_migration(root, "answer", FUNCTION_V1, "DROP VIEW answer;")
    write_migration(
        root, "reader", "CREATE TABLE reader (id int);", "DROP TABLE reader;", 'dependencies = ["answer"]\n'
    )
    commit_all(root, "before rework")
    base = git(root, "branch", "--show-current")

    git(root, "checkout", "-b", "reworked")
    write_migration(root, "answer@1", FUNCTION_V1, "DROP VIEW answer;", 'id = "answer"\n')
    write_migration(root, "answer", FUNCTION_V2, FUNCTION_V1, 'id = "answer@2"\ndependencies = ["answer"]\n')
    commit_all(root, "rework answer")
    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
    assert applied_ids(tmp_path) == {"answer", "reader", "answer@2"}
    history_before = len(audit(tmp_path))

    result = mitch("checkout", base, "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert audit(tmp_path)[history_before:] == [("answer@2", "reverted")]
    assert applied_ids(tmp_path) == {"answer", "reader"}


# ---------------------------------------------------------------- ordering constraints


def table(name: str) -> tuple[str, str]:
    return f"CREATE TABLE {name} (id int);", f"DROP TABLE {name};"


def test_ordering_constraint_runs_a_migration_after_another_in_the_same_run(tmp_path):
    root = new_project(tmp_path / "app")
    # Without the constraint, "early" would sort first by creation time.
    write_migration(root, "late", *table("late"), "created_at = 2026-02-01\n")
    write_migration(root, "early", *table("early"), 'created_at = 2026-01-01\nafter = ["late"]\n')

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert [m for m, _ in audit(tmp_path)] == ["late", "early"]


def test_ordering_constraint_does_not_pull_in_its_target(tmp_path):
    root = new_project(tmp_path / "app")
    write_migration(root, "optional", *table("optional"))
    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')

    result = mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert applied_ids(tmp_path) == {"main"}


def test_cycle_of_dependency_and_ordering_constraint_is_an_error(tmp_path):
    root = new_project(tmp_path / "app")
    write_migration(root, "a", *table("a"), 'after = ["b"]\n')
    write_migration(root, "b", *table("b"), 'dependencies = ["a"]\n')

    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "cycle" in result.output


def test_late_target_of_ordering_constraint_is_applied_with_a_warning(tmp_path):
    root = new_project(tmp_path / "app")
    write_migration(root, "optional", *table("optional"))
    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
    mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))

    result = mitch("add", "optional", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert "Warning" in result.output and "main" in result.output
    assert audit(tmp_path) == [("main", "applied"), ("optional", "applied")]


def test_restore_order_reverts_and_reapplies_around_a_late_target(tmp_path):
    root = new_project(tmp_path / "app")
    write_migration(root, "optional", *table("optional"))
    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
    mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))

    result = mitch("add", "optional", "--restore-order", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert audit(tmp_path)[1:] == [("main", "reverted"), ("optional", "applied"), ("main", "applied")]


def test_late_target_is_detected_through_the_recorded_constraint_of_a_project_not_loaded(tmp_path):
    users = new_project(tmp_path / "users", "org.example.users")
    write_migration(users, "create-users", *table("users"))
    reports = new_project(tmp_path / "reports", "org.example.reports")
    (reports / "mitch.toml").write_text(
        '[project]\nid = "org.example.reports"\n\n[projects]\nu = "../users"\n', encoding="utf-8"
    )
    write_migration(reports, "report", *table("report"), 'after = ["u:create-users"]\n')
    mitch("up", "-p", str(reports), "-d", db_url(tmp_path))
    assert applied_ids(tmp_path) == {"report"}

    result = mitch("up", "-p", str(users), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert "Warning" in result.output and "org.example.reports:report" in result.output


# ---------------------------------------------------------------- rebuild


def _view_project(tmp_path: Path, dependant_down: str | None = "DROP VIEW w;", extra_dependant: bool = False) -> Path:
    """base table, view v (migration x), view w on v (migration d, depends on x)."""
    root = new_project(tmp_path / "app")
    write_migration(root, "base", "CREATE TABLE base (id int, name text);", "DROP TABLE base;")
    write_migration(
        root, "x", "CREATE VIEW v AS SELECT id, name FROM base;", "DROP VIEW v;", 'dependencies = ["base"]\n'
    )
    write_migration(
        root, "d", "CREATE VIEW w AS SELECT id FROM v; SELECT id FROM w;", dependant_down, 'dependencies = ["x"]\n'
    )
    if extra_dependant:
        write_migration(
            root, "optional", "CREATE VIEW o AS SELECT id FROM v;", "DROP VIEW o;", 'dependencies = ["x"]\n'
        )
    return root


def _write_rebuilder(
    root: Path, up: str = "DROP VIEW v; CREATE VIEW v AS SELECT id FROM base;", extra: str = ""
) -> None:
    write_migration(
        root,
        "m",
        up,
        "DROP VIEW v; CREATE VIEW v AS SELECT id, name FROM base;",
        f'dependencies = ["x"]\nrebuild_dependants_of = ["x"]\n{extra}',
    )


def test_rebuild_reverts_applied_dependants_applies_the_migration_and_reapplies_them(tmp_path):
    root = _view_project(tmp_path, extra_dependant=True)
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
    _write_rebuilder(root)

    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert audit(tmp_path)[3:] == [("d", "reverted"), ("m", "applied"), ("d", "applied")]
    assert "optional" not in applied_ids(tmp_path)


def test_rebuild_is_refused_when_a_dependant_has_no_down_script(tmp_path):
    root = _view_project(tmp_path, dependant_down=None)
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
    _write_rebuilder(root)

    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "no down script" in result.output and "d" in result.output
    assert "m" not in applied_ids(tmp_path)


def test_rebuild_is_refused_when_a_dependant_belongs_to_a_project_that_is_not_loaded(tmp_path):
    root = _view_project(tmp_path)
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
    other = new_project(tmp_path / "other", "org.example.other")
    (other / "mitch.toml").write_text(
        '[project]\nid = "org.example.other"\n\n[projects]\napp = "../app"\n', encoding="utf-8"
    )
    write_migration(other, "uses-v", "CREATE VIEW u AS SELECT id FROM v;", "DROP VIEW u;", 'dependencies = ["app:x"]\n')
    mitch("up", "-p", str(other), "-d", db_url(tmp_path))
    _write_rebuilder(root)

    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "org.example.other:uses-v" in result.output
    assert "m" not in applied_ids(tmp_path)


def test_rebuild_with_non_transactional_participant_needs_allow_autocommit(tmp_path):
    root = _view_project(tmp_path)
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
    _write_rebuilder(root, extra="transactional = false\n")

    refused = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))
    allowed = mitch("add", "m", "--allow-autocommit", "-p", str(root), "-d", db_url(tmp_path))

    assert refused.exit_code == 1 and "--allow-autocommit" in refused.output
    assert allowed.exit_code == 0, allowed.output
    assert {"m", "d"} <= applied_ids(tmp_path)


def test_failed_autocommit_rebuild_prints_the_command_to_resume(tmp_path):
    root = _view_project(tmp_path)
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
    # The new v lacks the column w selects, so re-applying d fails after m was committed.
    _write_rebuilder(root, up="DROP VIEW v; CREATE VIEW v AS SELECT name FROM base;", extra="transactional = false\n")

    result = mitch("add", "m", "--allow-autocommit", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "mitch add d" in result.output


def test_database_error_during_rebuild_hints_at_an_undeclared_dependency(tmp_path):
    root = _view_project(tmp_path, dependant_down="DROP VIEW does_not_exist;")
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
    _write_rebuilder(root)

    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert "undeclared" in result.output
    assert applied_ids(tmp_path) == {"base", "x", "d"}


# ---------------------------------------------------------------- rework command

import tomllib  # noqa: E402


def _config(path: Path) -> dict:
    return tomllib.loads(path.read_text(encoding="utf-8"))


def _reworkable(tmp_path: Path) -> Path:
    """answer (idempotent view), reader and audit-reader depending on it, plus an unrelated table."""
    root = new_project(tmp_path / "app")
    write_migration(
        root,
        "answer",
        FUNCTION_V1,
        "DROP VIEW answer;",
        "created_at = 2026-01-01\nidempotent = true\ntransactional = true\n",
    )
    write_migration(root, "reader", *table("reader"), 'dependencies = ["answer"]\n')
    write_migration(root, "audit-reader", *table("audit_reader"), 'dependencies = ["reader"]\n')
    write_migration(root, "unrelated", *table("unrelated"))
    return root


def test_rework_archives_the_current_version_under_its_id_and_prepares_the_new_one(tmp_path):
    root = _reworkable(tmp_path)

    result = mitch("rework", "answer", "-p", str(root))

    assert result.exit_code == 0, result.output
    assert (root / "answer@1.up.sql").read_text(encoding="utf-8") == FUNCTION_V1
    assert (root / "answer@1.down.sql").read_text(encoding="utf-8") == "DROP VIEW answer;"
    archived = _config(root / "answer@1.config.toml")
    assert archived["id"] == "answer" and archived["idempotent"] is True
    assert str(archived["created_at"]) == "2026-01-01"

    assert (root / "answer.up.sql").read_text(encoding="utf-8") == FUNCTION_V1
    assert (root / "answer.down.sql").read_text(encoding="utf-8") == FUNCTION_V1
    new = _config(root / "answer.config.toml")
    assert new["id"] == "answer@2"
    assert new["dependencies"] == ["answer"]
    assert new["after"] == ["audit-reader", "reader"]
    assert new["idempotent"] is True and new["transactional"] is True
    assert str(new["created_at"]) != "2026-01-01"
    assert '# rebuild_dependants_of = ["answer"]' in (root / "answer.config.toml").read_text(encoding="utf-8")


def test_rework_again_archives_the_newest_version(tmp_path):
    root = _reworkable(tmp_path)
    mitch("rework", "answer", "-p", str(root))

    result = mitch("rework", "answer", "-p", str(root))

    assert result.exit_code == 0, result.output
    assert _config(root / "answer@2.config.toml")["id"] == "answer@2"
    assert _config(root / "answer.config.toml")["id"] == "answer@3"
    assert _config(root / "answer.config.toml")["dependencies"] == ["answer@2"]
    assert _config(root / "answer.config.toml")["after"] == ["audit-reader", "reader"]
    assert '# rebuild_dependants_of = ["answer", "answer@2"]' in (root / "answer.config.toml").read_text(
        encoding="utf-8"
    )
    assert _config(root / "answer@1.config.toml")["id"] == "answer"


def test_rework_of_unknown_migration_fails_without_creating_files(tmp_path):
    root = _reworkable(tmp_path)
    before = sorted(p.name for p in root.iterdir())

    result = mitch("rework", "nope", "-p", str(root))

    assert result.exit_code == 1
    assert sorted(p.name for p in root.iterdir()) == before


def test_rework_rejects_migrations_of_linked_projects(tmp_path):
    root = _reworkable(tmp_path)
    users = new_project(root / "users", "org.example.users")
    write_migration(users, "create-users", *table("users"))

    result = mitch("rework", "users:create-users", "-p", str(root))

    assert result.exit_code == 1
    assert not (users / "create-users@1.up.sql").exists()


def test_rework_gives_old_and_fresh_deployments_the_same_history(tmp_path):
    root = _reworkable(tmp_path)
    old_db, fresh_db = tmp_path / "old.db", tmp_path / "fresh.db"
    assert mitch("up", "-p", str(root), "-d", f"sqlite:///{old_db}").exit_code == 0
    mitch("rework", "answer", "-p", str(root))
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")

    assert mitch("up", "-p", str(root), "-d", f"sqlite:///{old_db}").exit_code == 0
    assert mitch("up", "-p", str(root), "-d", f"sqlite:///{fresh_db}").exit_code == 0

    def history(db: Path) -> list[str]:
        with sqlite3.connect(db) as connection:
            rows = connection.execute("SELECT migration_id FROM mitch_migration_audit ORDER BY id").fetchall()
        return [row[0] for row in rows if row[0] != "unrelated"]

    assert history(old_db) == history(fresh_db) == ["answer", "reader", "audit-reader", "answer@2"]


def test_applying_a_reworked_version_does_not_roll_out_optional_dependants(tmp_path):
    root = _reworkable(tmp_path)
    mitch("rework", "answer", "-p", str(root))

    result = mitch("add", "answer@2", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert applied_ids(tmp_path) == {"answer", "answer@2"}


def test_status_suggests_rework_for_an_edited_idempotent_migration(tmp_path):
    root = _reworkable(tmp_path)
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")

    result = mitch("status", "--no-ci", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0
    assert "M answer" in result.output
    assert "mitch rework answer" in result.output


def test_status_and_log_group_versions_of_a_migration(tmp_path):
    root = _reworkable(tmp_path)
    write_migration(root, "answer-cache", *table("answer_cache"))
    mitch("rework", "answer", "-p", str(root))

    status = mitch("status", "--no-ci", "-p", str(root), "-d", db_url(tmp_path))
    lines = [line[2:] for line in status.output.splitlines() if line.startswith("A ")]
    assert lines.index("answer@2") == lines.index("answer") + 1

    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
    log = mitch("log", "-p", str(root), "-d", db_url(tmp_path))
    assert log.output.index("answer@2") < log.output.index("reader")
    assert log.output.index("reader") < log.output.index("audit-reader")


# ---------------------------------------------------------------- review findings


def test_restore_order_still_rebuilds_dependants(tmp_path):
    root = _view_project(tmp_path)
    write_migration(root, "optional", *table("optional"))
    write_migration(root, "late", *table("late"), 'after = ["optional"]\n')
    mitch("add", "d", "late", "-p", str(root), "-d", db_url(tmp_path))
    _write_rebuilder(root)

    result = mitch("add", "optional", "m", "--restore-order", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert ("d", "reverted") in audit(tmp_path)


def test_allow_autocommit_keeps_a_fully_transactional_rebuild_atomic(tmp_path):
    root = _view_project(tmp_path)
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
    _write_rebuilder(root, up="DROP VIEW v; SELECT missing FROM nowhere;")

    result = mitch("add", "m", "--allow-autocommit", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 1
    assert applied_ids(tmp_path) == {"base", "x", "d"}
    assert ("d", "reverted") not in audit(tmp_path)


def _rework_branches(tmp_path: Path) -> tuple[Path, str]:
    """A repository whose current branch is before the rework and branch `reworked` after it."""
    root = _reworkable(tmp_path)
    init_repo(root)
    commit_all(root, "before rework")
    base = git(root, "branch", "--show-current")
    git(root, "checkout", "-b", "reworked")
    assert mitch("rework", "answer", "-p", str(root)).exit_code == 0
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
    commit_all(root, "rework answer")
    git(root, "checkout", base)
    return root, base


def test_checkout_forward_across_a_rework_reverts_nothing_and_leaves_the_new_version_pending(tmp_path):
    root, _ = _rework_branches(tmp_path)
    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
    history_before = len(audit(tmp_path))

    result = mitch("checkout", "reworked", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert len(audit(tmp_path)) == history_before
    assert "answer@2" not in applied_ids(tmp_path)


def test_stash_of_a_rework_in_progress_reverts_only_the_new_version(tmp_path):
    root = _reworkable(tmp_path)
    init_repo(root)
    commit_all(root, "before rework")
    mitch("rework", "answer", "-p", str(root))
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
    history_before = len(audit(tmp_path))

    result = mitch("stash", "-p", str(root), "-d", db_url(tmp_path))

    assert result.exit_code == 0, result.output
    assert audit(tmp_path)[history_before:] == [("answer@2", "reverted")]
    assert "answer@2" not in applied_ids(tmp_path)
