# -*- coding: utf-8 -*-
"""The whole curriculum, built once at import time, organised by course level (see levels.py)."""
from .levels import LEVELS as _LEVELS

def band_of(age):
    """Age group that sets the look, wording, ranks and avatars of a level."""
    if not age or age <= 9:
        return "kids"
    return "junior" if age <= 12 else "teen"


LEVELS = []          # metadata only (JSON-able): id, titles, book, available, counts
BY_LEVEL = {}        # level id -> list of units
for _l in _LEVELS:
    _units = _l["build"]() if _l["available"] and _l["build"] else []
    for _u in _units:
        _u["level"] = _l["id"]
    BY_LEVEL[_l["id"]] = _units
    _meta = {k: v for k, v in _l.items() if k != "build"}
    _meta.update(band=band_of(_l.get("age")), units=len(_units), lessons=sum(len(u["lessons"]) for u in _units),
                 activities=sum(len(l["activities"]) for u in _units for l in u["lessons"]))
    LEVELS.append(_meta)

AVAILABLE = [l["id"] for l in LEVELS if l["available"]]
UNITS = [u for lid in AVAILABLE for u in BY_LEVEL[lid]]          # every unit of every available level, level 1 first

LESSONS, ACTIVITIES, LEVEL_OF_ACTIVITY = {}, {}, {}
_unit_ids = set()
for _u in UNITS:
    assert _u["id"] not in _unit_ids, f"duplicate unit id {_u['id']}"
    _unit_ids.add(_u["id"])
    for _ls in _u["lessons"]:
        assert _ls["id"] not in LESSONS, f"duplicate lesson id {_ls['id']}"
        LESSONS[_ls["id"]] = _ls
        for _a in _ls["activities"]:
            assert _a["id"] not in ACTIVITIES, f"duplicate activity id {_a['id']}"
            ACTIVITIES[_a["id"]] = (_ls["id"], _a)
            LEVEL_OF_ACTIVITY[_a["id"]] = _u["level"]


def level(level_id):
    return next((l for l in LEVELS if l["id"] == level_id), None)


def units_of(level_id):
    return BY_LEVEL.get(level_id, [])


def outline(level_id=1):
    """Units/lessons of one level without activity data (for the dashboards)."""
    return [dict({k: v for k, v in u.items() if k != "lessons"},
                 lessons=[dict({k: v for k, v in l.items() if k != "activities"},
                               activities=[dict(id=a["id"], type=a["type"], title=a["title"], title_ar=a["title_ar"], points=a["points"])
                                           for a in l["activities"]]) for l in u["lessons"]]) for u in units_of(level_id)]
