#!/usr/bin/env python3
"""Migrate data from mcp-memory-service to claude-engram."""

import json
import sqlite3
import sys
from pathlib import Path

# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from claude_engram.storage import MemoryStorage

OLD_DB = Path.home() / ".local" / "share" / "mcp-memory" / "sqlite_vec.db"


def migrate():
    """Migrate memories from old mcp-memory-service."""
    if not OLD_DB.exists():
        print(f"No source database found at {OLD_DB}")
        return 0

    print(f"Source database: {OLD_DB}")

    # Connect to old database
    old_conn = sqlite3.connect(str(OLD_DB))
    old_conn.row_factory = sqlite3.Row

    # Get memories (exclude deleted)
    memories = old_conn.execute("""
        SELECT id, content, tags, memory_type, metadata, created_at_iso
        FROM memories
        WHERE deleted_at IS NULL
        ORDER BY created_at ASC
    """).fetchall()

    if not memories:
        print("No memories to migrate")
        return 0

    print(f"Found {len(memories)} memories to migrate")

    # Initialize new storage
    storage = MemoryStorage()

    migrated = 0
    for mem in memories:
        content = mem["content"]
        category = mem["memory_type"] or "general"

        # Parse metadata
        try:
            metadata = json.loads(mem["metadata"]) if mem["metadata"] else {}
        except json.JSONDecodeError:
            metadata = {}

        # Add migration info
        metadata["migrated_from"] = "mcp-memory-service"
        metadata["original_id"] = mem["id"]
        metadata["original_created"] = mem["created_at_iso"]

        # Store in new database
        try:
            new_id = storage.store(content=content, category=category, metadata=metadata)
            print(f"  Migrated #{mem['id']} -> #{new_id}: {content[:60]}...")
            migrated += 1
        except Exception as e:
            print(f"  Failed #{mem['id']}: {e}")

    storage.close()
    old_conn.close()

    print(f"\nMigrated {migrated}/{len(memories)} memories")
    return migrated


if __name__ == "__main__":
    migrate()
