"""Migration 008: Expand knowledge types and domains for personal + professional use.

Adds new entry_type values:
  mood, habit, goal, reflection, learning, values, relationship

Adds new domain values:
  personal, learning, health, relationships, career, creativity

Adds classification_level column to knowledge_entries:
  1 = public, 2 = team, 3 = personal, 4 = cognitive (never syncs)

Personal entry types are classification_level=4 by default (Cognitive,
never syncs to teams). This is the foundation for human-AI relationship tracking.
"""
from . import register

# Personal/cognitive entry types — classification_level=4, never sync
_COGNITIVE_TYPES = ("mood", "habit", "goal", "reflection", "learning", "values", "relationship")


@register(8, "Expand knowledge types and domains for personal + professional use")
def migrate(db) -> None:
    """Add classification_level column and record expanded types in metadata."""
    # Add classification_level column (default 3 = personal for existing entries)
    try:
        db.execute(
            "ALTER TABLE knowledge_entries ADD COLUMN classification_level "
            "INTEGER NOT NULL DEFAULT 3"
        )
    except Exception:
        pass  # Column already exists

    # Backfill existing personal-type entries to classification_level=4
    for entry_type in _COGNITIVE_TYPES:
        db.execute(
            "UPDATE knowledge_entries SET classification_level = 4 "
            "WHERE entry_type = ? AND classification_level != 4",
            (entry_type,),
        )

    # Record the expanded types and domains in metadata
    new_types = ",".join(_COGNITIVE_TYPES)
    new_domains = "personal,learning,health,relationships,career,creativity"

    db.execute(
        "INSERT INTO _schema_metadata (key, value) VALUES (?, ?) "
        "ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')",
        ("personal_knowledge_types", new_types, new_types),
    )
    db.execute(
        "INSERT INTO _schema_metadata (key, value) VALUES (?, ?) "
        "ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')",
        ("personal_knowledge_domains", new_domains, new_domains),
    )
