import os
import sqlite3
import subprocess
import sys
from pathlib import Path


def _write_executable(path: Path, content: str) -> None:
    path.write_text(content)
    path.chmod(0o755)


def test_legacy_database_starts_migrations_from_pre_alembic_baseline(tmp_path: Path) -> None:
    database_path = tmp_path / "legacy.db"
    connection = sqlite3.connect(database_path)
    connection.execute("CREATE TABLE scenarios (id TEXT PRIMARY KEY, name TEXT NOT NULL)")
    connection.close()

    command_log = tmp_path / "commands.log"
    bin_dir = tmp_path / "bin"
    bin_dir.mkdir()
    recorder = '#!/bin/sh\nprintf "%s\\n" "$*" >> "$COMMAND_LOG"\n'
    _write_executable(bin_dir / "alembic", recorder)
    _write_executable(bin_dir / "agenteval", recorder)
    _write_executable(bin_dir / "python", f'#!/bin/sh\nexec "{sys.executable}" "$@"\n')

    environment = {
        **os.environ,
        "AGENTEVAL_DB_PATH": str(database_path),
        "COMMAND_LOG": str(command_log),
        "PATH": f"{bin_dir}:{os.environ['PATH']}",
    }
    script = Path(__file__).resolve().parents[2] / "scripts" / "production-entrypoint.sh"

    subprocess.run(["sh", str(script)], check=True, env=environment)

    assert command_log.read_text().splitlines() == [
        "stamp base",
        "upgrade head",
        "server start --host 0.0.0.0 --port 8000",
    ]
