import json
import logging
from database import get_db

logger = logging.getLogger("melodies.database")


async def insert_melody(melody_id: str, status: str, data: dict) -> None:
    db = await get_db()
    await db.execute(
        "INSERT INTO melody_drafts (id, status, data) VALUES (?, ?, ?)",
        (melody_id, status, json.dumps(data)),
    )
    await db.commit()


async def update_melody(melody_id: str, data: dict) -> None:
    db = await get_db()
    await db.execute(
        "UPDATE melody_drafts SET data = ?, updated_at = datetime('now') WHERE id = ?",
        (json.dumps(data), melody_id),
    )
    await db.commit()


async def update_status(melody_id: str, status: str) -> None:
    db = await get_db()
    await db.execute(
        "UPDATE melody_drafts SET status = ?, updated_at = datetime('now') WHERE id = ?",
        (status, melody_id),
    )
    await db.commit()


async def get_melody(melody_id: str) -> dict | None:
    db = await get_db()
    rows = await db.execute_fetchall(
        "SELECT * FROM melody_drafts WHERE id = ?", (melody_id,)
    )
    if not rows:
        return None
    row = dict(rows[0])
    row["data"] = json.loads(row["data"])
    return row


async def list_melodies(status: str | None = None) -> list[dict]:
    db = await get_db()
    if status and status != "all":
        rows = await db.execute_fetchall(
            "SELECT * FROM melody_drafts WHERE status = ? ORDER BY updated_at DESC",
            (status,),
        )
    else:
        rows = await db.execute_fetchall(
            "SELECT * FROM melody_drafts ORDER BY updated_at DESC"
        )
    results = []
    for row in rows:
        r = dict(row)
        r["data"] = json.loads(r["data"])
        results.append(r)
    return results


async def delete_melody(melody_id: str) -> None:
    db = await get_db()
    await db.execute("DELETE FROM melody_drafts WHERE id = ?", (melody_id,))
    await db.commit()


async def count_melodies() -> int:
    db = await get_db()
    rows = await db.execute_fetchall("SELECT COUNT(*) FROM melody_drafts")
    return rows[0][0]
