from __future__ import annotations

import sqlite3

from backend.database.migrations.runner import Migration, MigrationError


REQUIRED_TABLES = frozenset(
    {
        "users",
        "user_sessions",
        "dashboard_snapshots",
        "watchlist",
        "review_notes",
        "stock_master",
        "daily_bars",
        "screener_runs",
        "mentor_messages",
        "trade_entries",
        "heaven_readings",
    }
)


def adopt_legacy_schema(connection: sqlite3.Connection) -> None:
    tables = {
        str(row["name"])
        for row in connection.execute(
            "SELECT name FROM sqlite_master WHERE type = 'table'"
        )
    }
    missing = sorted(REQUIRED_TABLES - tables)
    if missing:
        raise MigrationError(f"Legacy schema is incomplete: {', '.join(missing)}")


MIGRATION = Migration(
    version="0001",
    name="adopt_legacy_schema",
    action=adopt_legacy_schema,
    signature="required-tables:v1:" + ",".join(sorted(REQUIRED_TABLES)),
)
