"""create companion notes for existing tasks

Revision ID: 0003
Revises: 0002
Create Date: 2025-01-01 00:00:00.000000
"""

from alembic import op
import sqlalchemy as sa

revision = "0003"
down_revision = "0002"
branch_labels = None
depends_on = None


def upgrade() -> None:
    conn = op.get_bind()

    # Find tasks that don't have a companion note
    tasks = conn.execute(
        sa.text("SELECT id, title, tags FROM tasks WHERE note_id IS NULL")
    ).fetchall()

    for task in tasks:
        # Create a companion note
        result = conn.execute(
            sa.text(
                "INSERT INTO notes (title, body, tags, created_at, updated_at) "
                "VALUES (:title, '', :tags, NOW(), NOW()) RETURNING id"
            ),
            {"title": task.title, "tags": task.tags},
        )
        note_id = result.scalar()

        # Link the task to its companion note
        conn.execute(
            sa.text("UPDATE tasks SET note_id = :note_id WHERE id = :task_id"),
            {"note_id": note_id, "task_id": task.id},
        )


def downgrade() -> None:
    # Remove companion notes that were created by this migration
    # (notes linked to tasks that were previously unlinked)
    # This is a best-effort downgrade - we can't perfectly distinguish
    # migration-created notes from user-created ones
    pass
