import os
import pathlib
import sqlite3
import re
import pytest


def test_migration_file_exists_and_name():
    migrations_dir = pathlib.Path("migrations")
    expected_name = "2026-03-22-add-audit-events.sql"
    migration_path = migrations_dir / expected_name

    # File must exist
    assert migration_path.exists(), f"Migration file {migration_path} does not exist"

    # Name sanity check
    assert migration_path.name == expected_name


def _strip_sql_comments(sql_text: str) -> str:
    # Remove SQL single-line comments -- ... and C-style /* ... */
    # Use multiline-aware single-line removal for safety.
    no_single = re.sub(r"--.*?$", "", sql_text, flags=re.MULTILINE)
    no_block = re.sub(r"/\*.*?\*/", "", no_single, flags=re.DOTALL)
    return no_block.strip()


def test_optional_apply_sql_if_db_available():
    """
    If TEST_DB_URL is provided, attempt to apply the SQL.

    For safety this test will skip applying when the SQL is empty or commented out.
    Only sqlite URLs (sqlite:///path/to/db) are attempted here to avoid adding
    extra dependencies; other URL schemes will cause the test to be skipped.
    """
    db_url = os.environ.get("TEST_DB_URL")
    if not db_url:
        pytest.skip("TEST_DB_URL not set - skipping DB application")

    migration_path = pathlib.Path("migrations") / "2026-03-22-add-audit-events.sql"
    sql = migration_path.read_text(encoding="utf8")
    stripped = _strip_sql_comments(sql)
    if not stripped:
        pytest.skip("Migration SQL is empty or commented out - skipping application")

    # Only handle sqlite URLs here
    if db_url.startswith("sqlite:///"):
        db_path = db_url.replace("sqlite:///", "", 1)
        try:
            conn = sqlite3.connect(db_path)
            try:
                conn.executescript(sql)
            finally:
                conn.close()
        except Exception as e:
            pytest.skip(f"Could not apply SQL to sqlite DB: {e}")
    else:
        pytest.skip(f"TEST_DB_URL set but scheme not supported by this test: {db_url}")
