import shutil
import tempfile
from contextlib import nullcontext
from pathlib import Path
from types import SimpleNamespace

import pytest
import sqlalchemy as sa
from sqlalchemy import create_engine

from mitch.helpers import batch_transactional_migrations
from mitch.migration import Migration
from mitch.project import Project
from mitch.runner import Runner


@pytest.fixture
def project():
    yield Project.from_path(Path("tests/migrations"))


@pytest.fixture
def cloned_project(tmp_path):
    source = Path("tests/migrations")
    dest = tmp_path / "migrations"
    shutil.copytree(source, dest)
    yield Project.from_path(dest)


@pytest.fixture
def connection():
    engine = create_engine("sqlite:///:memory:", isolation_level="AUTOCOMMIT")
    with engine.connect() as conn:
        yield conn
    engine.dispose()


@pytest.fixture
def runner(connection):
    yield Runner(connection)


def _project_ref(project_id: str = "tests-runner") -> SimpleNamespace:
    return SimpleNamespace(id=project_id)



def test_runner_apply_migration(project, runner, connection):
    due_migrations = list(project.by_ids_with_dependencies(["001-init"]))

    # Check that the migrations are marked as applied
    for migration in due_migrations:
        assert 'pending' == runner.deployment_status(migration)

    # Apply migrations
    for transactional, migrations in batch_transactional_migrations(due_migrations):
        with runner.transaction() if transactional else nullcontext():
            runner.autocommit = not transactional
            for migration in migrations:
                runner.apply_migration(migration)
    
    # Check that the migrations are marked as applied
    for migration in due_migrations:
        assert 'applied' == runner.deployment_status(migration)
    
    # Check if some_table exists
    result = connection.execute(sa.text("SELECT name FROM sqlite_schema WHERE type='table' AND name='some_table'"))
    table = result.fetchone()
    assert table is not None
    assert table[0] == 'some_table'


def test_runner_deploy_migrations_batches_and_commits(tmp_path):
    db_path = tmp_path / "runner-deploy.db"
    engine = create_engine(f"sqlite:///{db_path}")

    up_script = tmp_path / "001-create.up.sql"
    up_script.write_text("CREATE TABLE deployed_with_batching (id int);", encoding="utf-8")
    migration = Migration(id="001-create", up_script=up_script, project=_project_ref("deploy-batches"))

    with engine.connect() as connection:
        runner = Runner(connection)
        runner.deploy_migrations([migration])

    with engine.connect() as connection:
        row = connection.execute(
            sa.text("SELECT id FROM mitch_migrations WHERE id = '001-create'")
        ).first()
        table = connection.execute(
            sa.text(
                "SELECT name FROM sqlite_schema WHERE type='table' AND name='deployed_with_batching'"
            )
        ).first()

    engine.dispose()

    assert row is not None
    assert table is not None


def test_runner_revert_migrations_batches_and_commits(tmp_path):
    db_path = tmp_path / "runner-revert.db"
    engine = create_engine(f"sqlite:///{db_path}")

    up_script = tmp_path / "001-create.up.sql"
    down_script = tmp_path / "001-create.down.sql"
    up_script.write_text("CREATE TABLE reverted_with_batching (id int);", encoding="utf-8")
    down_script.write_text("DROP TABLE reverted_with_batching;", encoding="utf-8")
    migration = Migration(
        id="001-create",
        up_script=up_script,
        down_script=down_script,
        project=_project_ref("revert-batches"),
    )

    with engine.connect() as connection:
        runner = Runner(connection)
        runner.deploy_migrations([migration])
        runner.revert_migrations([migration])

    with engine.connect() as connection:
        row = connection.execute(
            sa.text("SELECT id FROM mitch_migrations WHERE id = '001-create'")
        ).first()
        table = connection.execute(
            sa.text(
                "SELECT name FROM sqlite_schema WHERE type='table' AND name='reverted_with_batching'"
            )
        ).first()

    engine.dispose()

    assert row is None
    assert table is None


def test_runner_scopes_migration_ids_per_project(tmp_path):
    db_path = tmp_path / "runner-project-scope.db"
    engine = create_engine(f"sqlite:///{db_path}")

    migration_path = tmp_path / "001-shared.up.sql"
    migration_path.write_text("SELECT 1;", encoding="utf-8")
    migration_a = Migration(
        id="001-shared",
        up_script=migration_path,
        project=SimpleNamespace(id="project-a"),
    )
    migration_b = Migration(
        id="001-shared",
        up_script=migration_path,
        project=SimpleNamespace(id="project-b"),
    )

    with engine.connect() as connection:
        runner = Runner(connection)
        runner.deploy_migrations([migration_a])
        runner.deploy_migrations([migration_b])

        rows = connection.execute(
            sa.text("SELECT id FROM mitch_migrations WHERE id = '001-shared'")
        ).fetchall()

    engine.dispose()

    assert len(rows) == 2


def test_runner_uses_project_scoped_primary_key(runner):
    assert runner.project_table.name == "mitch_projects"
    assert [column.name for column in runner.migration_table.primary_key.columns] == ["project_id", "id"]


def test_runner_requires_parent_project_on_migrations(tmp_path, runner):
    up_script = tmp_path / "001-orphan.up.sql"
    up_script.write_text("SELECT 1;", encoding="utf-8")
    orphan = Migration(id="001-orphan", up_script=up_script)

    with pytest.raises(ValueError):
        runner.deploy_migrations([orphan])


def test_runner_split_statements_drops_empty(runner):
    statements = list(runner._split_statements("\n-- only a comment\n     \n"))
    assert statements == []


def test_setup_project_copies_migrations_isolated(cloned_project):
    original_sql = Path("tests/migrations/001-init.up.sql").read_text(encoding="utf-8")

    assert cloned_project.path.is_relative_to(Path(tempfile.gettempdir()))
    migration = cloned_project.by_id("001-init")
    modified_sql = original_sql + "\n-- mutated during test\n"
    migration.up_script.write_text(modified_sql, encoding="utf-8")
    assert migration.up_script.read_text(encoding="utf-8") == modified_sql

    unchanged_sql = Path("tests/migrations/001-init.up.sql").read_text(encoding="utf-8")
    assert unchanged_sql == original_sql


def test_runner_reapply_modified_migration_raises(cloned_project, runner):
    migration = cloned_project.by_id("001-init")
    runner.apply_migration(migration)

    modified_sql = (
        migration.up_script.read_text(encoding="utf-8")
        + "\nALTER TABLE some_table ADD COLUMN extra_col INTEGER;\n"
    )
    migration.up_script.write_text(modified_sql, encoding="utf-8")

    with pytest.raises(RuntimeError):
        runner.apply_migration(migration)


def test_runner_reapply_with_only_comments_or_whitespace_is_ok(cloned_project, runner):
    migration = cloned_project.by_id("001-init")
    runner.apply_migration(migration)

    original_sql = migration.up_script.read_text(encoding="utf-8")
    modified_sql = original_sql + "\n\n-- harmless comment\n\n"
    migration.up_script.write_text(modified_sql, encoding="utf-8")

    assert runner.deployment_status(migration) == "applied"
    runner.apply_migration(migration)


def test_runner_autocommit_toggles_isolation_level():
    class StubConnection:
        def __init__(self):
            self.default_isolation_level = "SERIALIZABLE"
            self._isolation_level = self.default_isolation_level
            self._in_tx = False
            self._in_nested = False

        def get_isolation_level(self):
            return self._isolation_level

        def execution_options(self, isolation_level):
            self._isolation_level = isolation_level
            return self

        def in_transaction(self):
            return self._in_tx

        def in_nested_transaction(self):
            return self._in_nested

        def commit(self):
            return None

    runner = Runner.__new__(Runner)
    runner.connection = StubConnection()
    runner._pending_work = []

    assert runner.autocommit is False
    runner.autocommit = True
    assert runner.autocommit is True
    runner.autocommit = False
    assert runner.autocommit is False


def test_runner_statements_from_file_requires_existing_path(tmp_path, runner):
    missing = tmp_path / "missing.sql"
    with pytest.raises(FileExistsError):
        list(runner._statements_from_file(missing))

    sql_file = tmp_path / "valid.sql"
    sql_file.write_text("SELECT 1; -- comment\n\n", encoding="utf-8")
    assert list(runner._statements_from_file(sql_file)) == ["select 1"]


def test_runner_transaction_rolls_back_on_error(runner):
    with pytest.raises(RuntimeError):
        with runner.transaction():
            raise RuntimeError("boom")


def test_runner_deployment_status_updates_normalized_hash(cloned_project, runner, connection):
    migration = cloned_project.by_id("001-init")
    runner.apply_migration(migration)
    project_local_id = runner.project_local_id_for(migration.project.id)

    connection.execute(
        runner.migration_table.update()
            .where(runner._migration_scope_for_id(project_local_id, migration.id))
            .values(normalized_hash="bad-hash")
    )

    assert runner.deployment_status(migration) == "applied"

    updated = connection.execute(
        runner.migration_table.select().where(runner._migration_scope_for_id(project_local_id, migration.id))
    ).first()
    assert updated.normalized_hash != "bad-hash"


def test_runner_revert_migration_applied(tmp_path, runner):
    up_script = tmp_path / "010-create.up.sql"
    down_script = tmp_path / "010-create.down.sql"
    up_script.write_text("CREATE TABLE revert_table (id int);", encoding="utf-8")
    down_script.write_text("DROP TABLE revert_table;", encoding="utf-8")

    migration = Migration(
        id="010-create",
        up_script=up_script,
        down_script=down_script,
        project=_project_ref("revert-applied"),
    )

    runner.apply_migration(migration)
    runner.revert_migration(migration)

    assert runner.deployment_status(migration) == "pending"


def test_runner_revert_migration_pending_is_noop(tmp_path, runner):
    up_script = tmp_path / "020-noop.up.sql"
    up_script.write_text("CREATE TABLE noop_table (id int);", encoding="utf-8")
    migration = Migration(id="020-noop", up_script=up_script, project=_project_ref("revert-noop"))

    runner.revert_migration(migration)

    assert runner.deployment_status(migration) == "pending"


def test_runner_revert_migration_modified(tmp_path, runner):
    up_script = tmp_path / "030-modified.up.sql"
    down_script = tmp_path / "030-modified.down.sql"
    up_script.write_text("CREATE TABLE mod_table (id int);", encoding="utf-8")
    down_script.write_text("DROP TABLE mod_table;", encoding="utf-8")

    migration = Migration(
        id="030-modified",
        up_script=up_script,
        down_script=down_script,
        project=_project_ref("revert-modified"),
    )
    runner.apply_migration(migration)

    up_script.write_text("CREATE TABLE mod_table (id int, name text);", encoding="utf-8")
    assert runner.deployment_status(migration) == "modified"

    runner.revert_migration(migration)

    assert runner.deployment_status(migration) == "pending"


def test_runner_apply_migration_ignores_unknown_status(monkeypatch, runner):
    migration = Migration(id="999-unknown", up_script=Path("999-unknown.up.sql"))
    monkeypatch.setattr(runner, "deployment_status", lambda _migration: "unknown")

    runner.apply_migration(migration)


def test_runner_revert_migration_ignores_unknown_status(monkeypatch, runner):
    migration = Migration(id="998-unknown", up_script=Path("998-unknown.up.sql"))
    monkeypatch.setattr(runner, "deployment_status", lambda _migration: "unknown")

    runner.revert_migration(migration)


def test_runner_ensure_migration_tables_with_schema_support(monkeypatch):
    class FakeDialect:
        supports_schemas = True
        name = "postgresql"

        def has_schema(self, _connection, _schema_name):
            return False

    class FakeConnection:
        def __init__(self):
            self.dialect = FakeDialect()
            self.executed = []

        def execute(self, statement):
            self.executed.append(str(statement))
            return None

    runner = Runner.__new__(Runner)
    runner.connection = FakeConnection()
    runner._pending_work = []

    monkeypatch.setattr(sa.MetaData, "create_all", lambda self, conn, checkfirst=True: None)

    runner._ensure_migration_tables()

    assert runner.metadata.schema == "mitch"
    assert "CREATE SCHEMA mitch" in runner.connection.executed[0]


def test_runner_ensure_migration_tables_schema_already_exists(monkeypatch):
    class FakeDialect:
        supports_schemas = True
        name = "postgresql"

        def has_schema(self, _connection, _schema_name):
            return True

    class FakeConnection:
        def __init__(self):
            self.dialect = FakeDialect()
            self.executed = []

        def execute(self, statement):
            self.executed.append(str(statement))
            return None

    runner = Runner.__new__(Runner)
    runner.connection = FakeConnection()
    runner._pending_work = []

    monkeypatch.setattr(sa.MetaData, "create_all", lambda self, conn, checkfirst=True: None)

    runner._ensure_migration_tables()

    assert runner.metadata.schema == "mitch"
    assert runner.connection.executed == []
