"""Builds a ready-made Tasker "Widget v2" custom layout (JSON).

Two designs:
  columns (default)  three columns - Overdue | Today | Tomorrow - on a transparent
                     background, underlined headers, blue MM-DD dates.
  card               the earlier single-column card (?style=card).

Tasker fetches /api/widget/tasker?key=... with an HTTP Request action and puts
%http_data straight into Widget v2's Custom Layout field, so the whole design
lives here, on the server.

Layout reference: https://tasker.joaoapps.com/userguide/en/widgetv2_custom.html
Notes: a non-scrolling container may hold at most 10 children, so every row
goes directly into the root Column, which scrolls.
"""

THEMES = {
    "dark": {"bg": "#1C1D1F", "text": "#F1F1F2", "muted": "#9B9CA1",
             "accent": "#3CC4A3", "danger": "#FF6B6B", "line": "#2E3033"},
    "light": {"bg": "#FFFFFF", "text": "#1C1C1E", "muted": "#6D6D72",
              "accent": "#11735F", "danger": "#D63939", "line": "#E4E2DC"},
}
PRIORITY_COLORS = {1: "#3B82F6", 2: "#E8890C"}
MAX_ROWS = 40

OPEN_TASK = "Todo Open"        # Tasker task run when the widget is tapped
REFRESH_TASK = "Todo Refresh"  # Tasker task run when the header is tapped


def _text(text, color, size=13, bold=False, max_lines=1, weighted=False, width=None, **extra):
    # A zero-width space after '%' stops Tasker reading "%word" in a title as a variable.
    text = str(text).replace("%", "%​")
    el = {"type": "Text", "text": text, "color": color, "textSize": size, "maxLines": max_lines}
    if bold:
        el["bold"] = True
    if weighted:
        el["isWeighted"] = True
    if width:
        el["width"] = width
    el.update(extra)
    return el


def _spacer(width=None, weighted=False):
    el = {"type": "Spacer"}
    if width:
        el["width"] = width
    if weighted:
        el["isWeighted"] = True
    return el


def _row(children, top=3):
    return {"type": "Row", "fillMaxWidth": True, "verticalAlignment": "Center",
            "paddingTop": top, "children": children}


def _section(label, c, color=None, top=10):
    return _text(label, color or c["accent"], size=11, bold=True, paddingTop=top)


def _task_row(t, c, overdue=False):
    p = t["priority"]
    dot_color = c["danger"] if p == 3 else PRIORITY_COLORS.get(p, c["muted"])
    if overdue:
        right, right_color = ("yesterday" if t["overdue_days"] == 1 else f"{t['overdue_days']}d late"), c["danger"]
    else:
        right, right_color = t["time_label"], c["muted"]
    kids = [_text("○", dot_color, size=14, width=16),
            _text(t["title"], c["text"], weighted=True)]
    if t.get("repeat_text"):
        kids.append(_text("↻", c["muted"], size=11, paddingStart=4))
    if right:
        kids.append(_text(right, right_color, size=11, paddingStart=6))
    return _row(kids)


def _color(value, fallback):
    return value if isinstance(value, str) and value.startswith("#") and len(value) in (4, 7, 9) else fallback


def _event_row(e, c):
    return _row([
        {"type": "Box", "width": 3, "height": 15, "cornerRadius": 2,
         "backgroundColor": _color(e.get("color"), c["accent"])},
        _spacer(width=8),
        _text("All day" if e["all_day"] else e["start_label"], c["muted"], size=12, width=62),
        _text(e["summary"], c["text"], weighted=True),
    ])


def build(data: dict, theme: str = "dark") -> dict:
    """data: today_label, tomorrow_label, updated, overdue, today_tasks, tomorrow_tasks,
    events_today/events_tomorrow (optional), tag (optional)."""
    c = THEMES.get(theme, THEMES["dark"])
    rows = []

    header = _row([
        _text(data["today_label"] + (f"  #{data['tag']}" if data.get("tag") else ""),
              c["text"], size=15, bold=True, weighted=True),
        _text(f"↻ {data['updated']}", c["muted"], size=11, task=REFRESH_TASK),
    ], top=0)

    if data["overdue"]:
        rows.append(_section(f"OVERDUE · {len(data['overdue'])}", c, color=c["danger"]))
        rows += [_task_row(t, c, overdue=True) for t in data["overdue"]]

    for label, tasks, events in (("TODAY", data["today_tasks"], data.get("events_today", [])),
                                 (f"TOMORROW · {data['tomorrow_label']}", data["tomorrow_tasks"],
                                  data.get("events_tomorrow", []))):
        rows.append(_section(f"{label} · {len(tasks)}" if tasks else label, c))
        rows += [_event_row(e, c) for e in events]
        rows += [_task_row(t, c) for t in tasks]
        if not tasks and not events:
            rows.append(_text("Nothing scheduled", c["muted"], size=12, paddingTop=3))

    if len(rows) > MAX_ROWS:
        hidden = len(rows) - MAX_ROWS + 1
        rows = rows[:MAX_ROWS - 1] + [_text(f"+{hidden} more · open Todo", c["muted"], size=11, paddingTop=4)]

    return {
        "type": "Column",
        "fillMaxSize": True,
        "backgroundColor": c["bg"],
        "cornerRadius": 22,
        "padding": 14,
        "scrolling": True,
        "task": OPEN_TASK,
        "children": [header] + rows,
    }


# --------------------------------------------------------------------------
# "columns" design (default)
# --------------------------------------------------------------------------
COLUMNS = {"header": "#FFFFFF", "text": "#FFFFFF", "date": "#5AA6F2",
           "muted": "#C9CDD2", "empty": "#AEB4BA", "bg": "#00000000", "line": "#80FFFFFF"}
EVENTS_PER_DAY = 9   # + "+N more" = 10 children
PER_COLUMN = 8   # Widget v2 containers hold at most 10 children: header + 8 + "+N more"


def _short(title: str, chars: int) -> str:
    title = " ".join(title.split())
    return title if len(title) <= chars else title[:max(1, chars - 1)].rstrip() + "…"


def _mmdd(iso_date) -> str:
    return f"{iso_date[5:7]}-{iso_date[8:10]}" if iso_date else ""


def _column(header: str, tasks, chars: int, c: dict) -> dict:
    kids = [_text(header, c["header"], size=16, underline=True, paddingBottom=4)]
    for t in tasks[:PER_COLUMN]:
        kids.append({"type": "Row", "fillMaxWidth": True, "verticalAlignment": "Center", "paddingTop": 2,
                     "children": [
                         _text(_mmdd(t["due_date"]), c["date"], size=14),
                         _spacer(width=6),
                         _text(_short(t["title"], chars), c["text"], size=14, weighted=True),
                     ]})
    if len(tasks) > PER_COLUMN:
        kids.append(_text(f"+{len(tasks) - PER_COLUMN} more", c["muted"], size=12, paddingTop=2))
    if not tasks:
        kids.append(_text("Nothing due", c["empty"], size=13, paddingTop=2))
    return {"type": "Column", "isWeighted": True, "paddingEnd": 8, "children": kids}


def _event_label(e) -> str:
    """'3:45PM', 'All day', 'until 3PM' - compact like the rest of the widget."""
    if e["all_day"]:
        return "All day"
    return e["start_label"].replace(" AM", "AM").replace(" PM", "PM")


def _events_block(label: str, sub: str, events, chars: int, c: dict) -> dict:
    items = [_text(f"{_event_label(e)} {_short(e['summary'], chars)}", _color(e.get("color"), c["text"]),
                   size=14, paddingTop=2)
             for e in events[:EVENTS_PER_DAY]]
    if len(events) > EVENTS_PER_DAY:
        items.append(_text(f"+{len(events) - EVENTS_PER_DAY} more", c["muted"], size=12, paddingTop=2))
    if not events:
        items.append(_text("No events", c["text"], size=14, paddingTop=2))
    return {"type": "Row", "fillMaxWidth": True, "verticalAlignment": "Top", "paddingTop": 8, "children": [
        {"type": "Column", "width": 92, "children": [
            _text(label, c["header"], size=18), _text(sub, c["header"], size=18)]},
        {"type": "Column", "isWeighted": True, "children": items},
    ]}


def build_columns(data: dict, chars: int = 16, bg: str = None) -> dict:
    """data: today_short ('Nov 15'), tomorrow_short, updated_full ('11/15 08:05PM'),
    overdue, today_tasks, tomorrow_tasks, tag (optional),
    show_events + events_today/events_tomorrow (optional)."""
    c = dict(COLUMNS)
    if bg:
        c["bg"] = bg
    tag = f" #{data['tag']}" if data.get("tag") else ""
    columns = {"type": "Row", "fillMaxWidth": True, "verticalAlignment": "Top", "children": [
        _column("Overdue" + tag, data["overdue"], chars, c),
        _column(f"Today {data['today_short']}", data["today_tasks"], chars, c),
        _column(f"Tomorrow {data['tomorrow_short']}", data["tomorrow_tasks"], chars, c),
    ]}
    footer = {"type": "Row", "fillMaxWidth": True, "paddingTop": 6, "children": [
        _spacer(weighted=True),
        _text(f"Updated {data['updated_full']}", c["muted"], size=12, task=REFRESH_TASK),
    ]}
    children = [columns, footer]
    if data.get("show_events"):
        children += [
            {"type": "Box", "fillMaxWidth": True, "height": 1, "backgroundColor": c["line"], "paddingTop": 4},
            _events_block("Today", data["today_short"], data.get("events_today", []), chars + 6, c),
            _events_block("Tomorrow", data["tomorrow_short"], data.get("events_tomorrow", []), chars + 6, c),
        ]
    return {
        "type": "Column",
        "fillMaxSize": True,
        "backgroundColor": c["bg"],
        "padding": 6,
        "task": OPEN_TASK,
        "children": children,
    }
