"""Migration 009: Add knowledge freshness categories with TTL-based staleness.

Adds knowledge_category and ttl_days columns to knowledge_entries.
Auto-classifies existing entries using keyword-based categorization.

Categories and TTLs:
    infrastructure   — 7 days
    architecture     — 14 days
    configuration    — 14 days
    correction       — 30 days
    process          — 30 days
    pattern          — 60 days
    domain_expertise — 90 days (default)
"""
from . import register


@register(9, "Add knowledge freshness categories with TTL-based staleness")
def migrate(db) -> None:
    """Add knowledge_category and ttl_days columns, classify existing entries."""
    # Add new columns
    try:
        db.execute(
            "ALTER TABLE knowledge_entries ADD COLUMN knowledge_category "
            "TEXT DEFAULT 'domain_expertise'"
        )
    except Exception:
        pass  # Column already exists

    try:
        db.execute(
            "ALTER TABLE knowledge_entries ADD COLUMN ttl_days "
            "INTEGER DEFAULT 90"
        )
    except Exception:
        pass  # Column already exists

    # Backfill existing entries using keyword-based classification.
    # We do this in Python rather than SQL so we can reuse the categorizer logic.
    try:
        from greymatter_core.knowledge_categorizer import classify_entry

        entries = db.execute(
            "SELECT id, entry_type, domain, title, content "
            "FROM knowledge_entries WHERE pruned_at IS NULL"
        )

        for entry in entries:
            category, ttl = classify_entry(entry)
            db.execute(
                "UPDATE knowledge_entries "
                "SET knowledge_category = ?, ttl_days = ? "
                "WHERE id = ?",
                (category, ttl, entry["id"]),
            )
    except Exception:
        # If categorizer import fails, entries keep the default
        # (domain_expertise, 90 days). They'll be classified on next access.
        pass

    # Record migration metadata
    db.execute(
        "INSERT INTO _schema_metadata (key, value) VALUES (?, ?) "
        "ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')",
        (
            "knowledge_categories",
            "infrastructure,architecture,configuration,correction,process,pattern,domain_expertise",
            "infrastructure,architecture,configuration,correction,process,pattern,domain_expertise",
        ),
    )
