"""Convert location attribute values from string to dict format

Revision ID: 0284
Revises: 0283
Create Date: 2025-12-18

"""

from alembic import op
import sqlalchemy as sa
import json


# revision identifiers, used by Alembic.
revision = "0284"
down_revision = "0283"
branch_labels = None
depends_on = None


def convert_to_dict(value):
    """Convert a location value to the new dict format."""
    if value is None:
        return None

    # Try to parse as JSON first
    if isinstance(value, str):
        try:
            parsed = json.loads(value)
            if isinstance(parsed, list):
                parsed = parsed[0]
            if isinstance(parsed, dict) and "address" in parsed:
                # Already in new format
                return parsed
            # It was a JSON string (e.g., "\"123 Main St\"")
            if isinstance(parsed, str):
                return {"address": parsed, "lat": None, "lng": None}
        except (json.JSONDecodeError, TypeError):
            pass
        # Plain string address
        return {"address": value, "lat": None, "lng": None}

    if isinstance(value, dict):
        if "address" in value:
            return value
        return {"address": str(value), "lat": None, "lng": None}

    return {"address": str(value), "lat": None, "lng": None}


def upgrade():
    conn = op.get_bind()

    # Find all location attribute values
    result = conn.execute(
        sa.text("""
        SELECT id, value
        FROM card_attributes
        WHERE type_name = 'location' AND value IS NOT NULL
    """)
    )

    updates = []
    for row in result:
        new_value = convert_to_dict(row[1])
        updates.append({"value": json.dumps(new_value), "id": row[0]})

    if updates:
        conn.execute(
            sa.text("UPDATE card_attributes SET value = :value WHERE id = :id"),
            updates
        )


def downgrade():
    pass
