"""Database migration from v0.1 to v0.2."""

from __future__ import annotations

import logging
import sqlite3

logger = logging.getLogger(__name__)

V02_MIGRATIONS = [
    """
    CREATE TABLE IF NOT EXISTS concept_hierarchy (
        id               BLOB PRIMARY KEY,
        child_entity_id  BLOB NOT NULL REFERENCES entities(id),
        parent_entity_id BLOB NOT NULL REFERENCES entities(id),
        relation_type    TEXT NOT NULL,
        confidence       REAL DEFAULT 0.8,
        source           TEXT DEFAULT 'inferred',
        created_at       INTEGER NOT NULL,
        UNIQUE(child_entity_id, parent_entity_id, relation_type)
    )
    """,
    """
    CREATE TABLE IF NOT EXISTS concept_properties (
        id               BLOB PRIMARY KEY,
        entity_id        BLOB NOT NULL REFERENCES entities(id),
        property_key     TEXT NOT NULL,
        property_value   TEXT NOT NULL,
        confidence       REAL DEFAULT 0.7,
        source_memory_id BLOB,
        created_at       INTEGER NOT NULL,
        UNIQUE(entity_id, property_key)
    )
    """,
    """
    CREATE TABLE IF NOT EXISTS plugin_state (
        plugin_id    TEXT PRIMARY KEY,
        enabled      INTEGER DEFAULT 1,
        config       TEXT DEFAULT '{}',
        last_poll    INTEGER DEFAULT 0,
        error_count  INTEGER DEFAULT 0,
        installed_at INTEGER NOT NULL
    )
    """,
    """
    CREATE TABLE IF NOT EXISTS hook_registry (
        id             INTEGER PRIMARY KEY AUTOINCREMENT,
        event          TEXT NOT NULL,
        handler_module TEXT NOT NULL,
        handler_func   TEXT NOT NULL,
        enabled        INTEGER DEFAULT 1,
        created_at     INTEGER NOT NULL
    )
    """,
    """
    CREATE TABLE IF NOT EXISTS processing_log (
        memory_id    BLOB NOT NULL,
        phase        TEXT NOT NULL,
        processed_at INTEGER NOT NULL,
        PRIMARY KEY (memory_id, phase)
    )
    """,
    "CREATE INDEX IF NOT EXISTS idx_ch_child ON concept_hierarchy(child_entity_id)",
    "CREATE INDEX IF NOT EXISTS idx_ch_parent ON concept_hierarchy(parent_entity_id)",
    "CREATE INDEX IF NOT EXISTS idx_cp_entity ON concept_properties(entity_id)",
    "CREATE INDEX IF NOT EXISTS idx_pl_phase ON processing_log(phase)",
    """
    CREATE TABLE IF NOT EXISTS schema_info (
        key TEXT PRIMARY KEY,
        value TEXT
    )
    """,
    "INSERT OR REPLACE INTO schema_info (key, value) VALUES ('version', '0.2.0')",
]


def _parse_version_tuple(raw: str) -> tuple[int, int, int]:
    parts = [p for p in str(raw).split(".") if p != ""]
    values: list[int] = []
    for part in parts[:3]:
        try:
            values.append(int(part))
        except ValueError:
            values.append(0)
    while len(values) < 3:
        values.append(0)
    return values[0], values[1], values[2]


def migrate_v01_to_v02(db_path: str) -> bool:
    """Run v0.1 to v0.2 database migration."""
    conn = sqlite3.connect(db_path)

    try:
        try:
            row = conn.execute("SELECT value FROM schema_info WHERE key = 'version'").fetchone()
            current_version = row[0] if row else "0.1.0"
        except Exception:
            current_version = "0.1.0"
            conn.execute("CREATE TABLE IF NOT EXISTS schema_info (key TEXT PRIMARY KEY, value TEXT)")

        if _parse_version_tuple(current_version) >= _parse_version_tuple("0.2.0"):
            logger.info("Database already at v0.2.0+, skipping migration")
            return True

        logger.info("Migrating database from %s to 0.2.0...", current_version)

        for sql in V02_MIGRATIONS:
            try:
                conn.execute(sql.strip())
            except sqlite3.OperationalError as exc:
                if "already exists" not in str(exc):
                    logger.warning("Migration SQL warning: %s", exc)

        conn.commit()
        logger.info("Migration to v0.2.0 complete")
        return True

    except Exception as exc:
        logger.error("Migration failed: %s", exc)
        conn.rollback()
        return False
    finally:
        conn.close()
