import logging
from datetime import timedelta

from django.conf import settings
from scrobbles.models import Scrobble

logger = logging.getLogger(__name__)


def get_title_from_labels(
    labels: list[str], user_context_labels: list[str] = []
) -> str:
    title = "Unknown"
    for label in labels:
        label = label.capitalize()
        if label in user_context_labels:
            title = label
            continue

    if title == "Unknown":
        logger.warning(
            "Missing a configured title context for task",
            extra={
                "labels": labels,
                "user_context_labels": user_context_labels,
            },
        )
    return title


def convert_old_orgmode_log_to_new(commit=False):
    scrobbles = Scrobble.objects.filter(
        source="Org-mode", log__has_key="drawers"
    )
    for scrobble in scrobbles:
        scrobble.log["title"] = scrobble.log.pop("description")
        scrobble.log["description"] = scrobble.log.pop("details")

        scrobble.log["orgmode_body"] = scrobble.log.pop("body")
        scrobble.log["orgmode_state"] = scrobble.log.pop("state")
        scrobble.log["orgmode_properties"] = scrobble.log.pop("properties")
        scrobble.log["orgmode_drawers"] = scrobble.log.pop("drawers")
        scrobble.log["orgmode_timestamps"] = scrobble.log.pop("timestamps")
        scrobble.log["orgmode_id"] = scrobble.log.pop("source_id")

        if commit:
            scrobble.save(update_fields=["log"])
    print(f"Updated {scrobbles.count()} orgmode tasks logs")


def convert_old_todoist_log_to_new(commit=False):
    scrobbles = Scrobble.objects.filter(
        source="Todoist", log__has_key="todoist_type"
    )
    for scrobble in scrobbles:
        scrobble.log["title"] = scrobble.log.pop("description")
        scrobble.log["description"] = scrobble.log.pop("details")
        scrobble.log["todoist_id"] = scrobble.log.pop("source_id")
        scrobble.log["labels"] = scrobble.log.pop("todoist_label_list")

        scrobble.log.pop("todoist_type")
        scrobble.log.pop("todoist_event")

        print(f"Updating scrobble {scrobble.id}")
        if commit:
            scrobble.save(update_fields=["log"])
    print(f"Updated {scrobbles.count()} todoist tasks logs")


def convert_notes_to_dict(commit=False):
    scrobbles = Scrobble.objects.filter(log__notes__isnull=False)
    count = 0
    for scrobble in scrobbles:
        if isinstance(scrobble.log, str):
            print(f"Converting {scrobble} string note to dict")
            if scrobble.log.get("notes") == "":
                scrobble.log.pop("notes")
            key = str(int(scrobble.timestamp.timestamp()))
            notes = scrobble.log.pop("notes")
            scrobble.log = {}
            scrobble.log["notes"] = {key: notes}
            count += 1

        if isinstance(scrobble.log.get("notes"), list):
            note_list = scrobble.log.pop("notes")
            if all(isinstance(item, dict) for item in note_list):
                scrobble.log["notes"] = [
                    value for d in note_list for value in d.values()
                ]
            count += 1
        if commit:
            scrobble.save(update_fields=["log"])
    print(f"Updated {count} todoist tasks scrobbles")


def convert_old_boardgame_log_to_new(commit=False):
    scrobbles = Scrobble.objects.filter(
        board_game__isnull=False, log__has_key="notes"
    )
    for scrobble in scrobbles:
        if isinstance(scrobble.log.get("notes"), str):
            scrobble.log["notes"] = [scrobble.log.pop("notes")]

        if commit:
            scrobble.save(update_fields=["log"])
    print(f"Updated {scrobbles.count()} board game scrobbles")
