import json
from collections.abc import Iterable
from typing import TypedDict

from folkugat_web.dal.sql import get_connection
from folkugat_web.dal.sql.temes import properties as properties_dal
from folkugat_web.model.temes import Property, PropertyField

query = """ SELECT id, properties FROM temes """
PropertyRowTuple = tuple[int, str]


class OldPropertyRowDict(TypedDict):
    field: str
    value: str


def _build_property(tema_id: int, property_dict: OldPropertyRowDict) -> Property:
    return Property(
        id=None,
        tema_id=tema_id,
        field=PropertyField(property_dict["field"]),
        value=property_dict["value"],
    )


def _build_properties(row: PropertyRowTuple) -> list[Property]:
    tema_id = row[0]
    property_dicts: list[OldPropertyRowDict] = json.loads(row[1])
    return [_build_property(tema_id, property_dict) for property_dict in property_dicts]


with get_connection() as con:
    cur = con.cursor()
    _ = cur.execute(query)
    iter_rows: Iterable[PropertyRowTuple] = cur.fetchall()
    rows = list(map(_build_properties, iter_rows))

    _ = cur.execute("DELETE FROM tema_properties")
    for properties in rows:
        for property in properties:
            _ = properties_dal.insert_property(property=property, con=con)

    drop_query = """ ALTER TABLE temes DROP COLUMN properties"""
    _ = cur.execute(drop_query)


print("DONE!")
