"""Migration 001: Add sync tracking columns and _sync_log table.

Every syncable table gets _sync_version (monotonic counter) and
_node_id (origin node identifier). The _sync_log table records
all changes for delta sync.
"""
from . import register
from greymatter_core.sync import SYNC_TABLES


@register(1, "Add sync tracking columns and _sync_log table")
def migrate(db) -> None:
    """Add _sync_version, _node_id columns and _sync_log table."""
    # Create the sync log table
    db.execute("""
        CREATE TABLE IF NOT EXISTS _sync_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            table_name TEXT NOT NULL,
            row_id TEXT NOT NULL,
            operation TEXT NOT NULL,
            sync_version INTEGER NOT NULL,
            node_id TEXT NOT NULL,
            created_at TEXT DEFAULT (datetime('now'))
        )
    """)
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_sync_log_version "
        "ON _sync_log(sync_version)"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_sync_log_table "
        "ON _sync_log(table_name, sync_version)"
    )

    # Create the sync version counter table
    db.execute("""
        CREATE TABLE IF NOT EXISTS _sync_state (
            key TEXT PRIMARY KEY,
            value TEXT NOT NULL,
            updated_at TEXT DEFAULT (datetime('now'))
        )
    """)
    # Initialize version counter and node_id
    db.execute(
        "INSERT OR IGNORE INTO _sync_state (key, value) "
        "VALUES ('sync_version', '0')"
    )
    db.execute(
        "INSERT OR IGNORE INTO _sync_state (key, value) "
        "VALUES ('node_id', hex(randomblob(8)))"
    )

    # Add sync columns to each syncable table
    for table in SYNC_TABLES:
        for col, col_type in [
            ("_sync_version", "INTEGER DEFAULT 0"),
            ("_node_id", "TEXT DEFAULT ''"),
        ]:
            try:
                db.execute(
                    f"ALTER TABLE {table} ADD COLUMN {col} {col_type}"
                )
            except Exception:
                pass  # Column already exists
