from shared.firebase import get_db
from settings.models import MelodySettings, MelodySettingsUpdate

COLLECTION = "admin_settings"
DOC_ID = "melody_settings"


def get_melody_settings() -> MelodySettings:
    """Get melody settings from Firestore. Creates defaults if not found."""
    db = get_db()
    doc = db.collection(COLLECTION).document(DOC_ID).get()
    if doc.exists:
        settings = MelodySettings(**doc.to_dict())
        # Backfill newly introduced defaults into stored settings.
        db.collection(COLLECTION).document(DOC_ID).set(settings.model_dump())
        return settings
    # Create with defaults
    defaults = MelodySettings()
    db.collection(COLLECTION).document(DOC_ID).set(defaults.model_dump())
    return defaults


def update_melody_settings(data: MelodySettingsUpdate) -> MelodySettings:
    """Update melody settings. Only provided fields are updated."""
    db = get_db()
    doc_ref = db.collection(COLLECTION).document(DOC_ID)
    doc = doc_ref.get()

    if doc.exists:
        existing = doc.to_dict()
    else:
        existing = MelodySettings().model_dump()

    update_data = data.model_dump(exclude_none=True)
    existing.update(update_data)

    # Sort duration values
    if "duration_values" in existing:
        existing["duration_values"] = sorted(existing["duration_values"])

    normalized = MelodySettings(**existing)
    doc_ref.set(normalized.model_dump())
    return normalized
