"""
Phase 1 — Step 1.5: crm_sync_state  (SQLite → Postgres)

Simple key/value table — small, no FK deps.

Run on VPS:
    docker compose exec backend python -m migration.migrate_crm_sync_state
"""

import asyncio
import sys

from sqlalchemy.dialects.postgresql import insert as pg_insert

from crm.orm import CrmSyncState
from migration.utils import open_sqlite, AsyncPgSession, log_run, pg_count

SCRIPT = "migrate_crm_sync_state"


async def run() -> None:
    sqlite = await open_sqlite()
    rows = await sqlite.execute_fetchall("SELECT * FROM crm_sync_state")
    await sqlite.close()

    source_count = len(rows)
    print(f"Source (SQLite): {source_count} crm_sync_state rows")

    if source_count == 0:
        print("Nothing to migrate.")
        await log_run(SCRIPT, 0, 0, notes="source empty")
        return

    records = [{"key": r["key"], "value": r["value"]} for r in rows]

    async with AsyncPgSession() as session:
        async with session.begin():
            stmt = pg_insert(CrmSyncState).values(records)
            stmt = stmt.on_conflict_do_nothing(index_elements=["key"])
            await session.execute(stmt)
            dest_count = await pg_count(session, "crm_sync_state")

    if dest_count < source_count:
        msg = f"Count mismatch: source={source_count}  postgres={dest_count}"
        print(f"ERROR: {msg}", file=sys.stderr)
        await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
        sys.exit(1)

    print(f"Postgres: {dest_count} rows ✓")
    await log_run(SCRIPT, source_count, dest_count)


if __name__ == "__main__":
    asyncio.run(run())
