from noita.models import LogfileSubmission, Objectiv, DeathCounter
from noita.services.decode import parse_log, resolve


def parse_objectives_from_logfile(
    logfile: LogfileSubmission,
) -> list[tuple[str, str, str]]:
    """Parse a log file, and output a count for each ID."""
    file_data = logfile.file.read().decode()

    entries: list[tuple[str, str, str]] = []
    for entry in parse_log(file_data):
        idx, seed = resolve(entry["hash"], entry["ts"])

        if idx and seed:
            entries.append((idx, str(seed), entry["ts"]))

    return entries


def parse_objectives_and_store(logfile: LogfileSubmission) -> None:
    """Parse a logfile and store output."""

    if not logfile.user:
        return

    objectives = []
    deaths = []
    for idx, seed, ts in parse_objectives_from_logfile(logfile):
        if idx in {"-", "DEBUG", "polylan-mod"}:
            continue

        if idx == "DEATH":
            deaths.append(DeathCounter(user=logfile.user, seed=seed, seen_at=ts))
            continue

        objectives.append(
            Objectiv(
                objectiv_id=idx,
                user=logfile.user,
                first_seen_at=ts,
                seed=seed,
                submission=logfile,
            )
        )

    Objectiv.objects.bulk_create(
        objectives,
        update_conflicts=True,
        update_fields=["seed", "submission"],
        unique_fields=["objectiv_id", "user", "first_seen_at"],
    )

    DeathCounter.objects.bulk_create(deaths, ignore_conflicts=True)
