from __future__ import annotations

from html import escape

from .constants import TASK_PRIORITIES, TASK_STATUSES


def case_list(cases: list[dict]) -> str:
    if not cases:
        return "Heç bir iş tapılmadı."

    lines: list[str] = []
    for item in cases:
        case_id = escape(str(item.get("id", "")))
        number = escape(str(item.get("is_nomresi", "")))
        party = escape(str(item.get("terefin_adi", "")))
        court = escape(str(item.get("mehkemenin_adi", "")))
        judge = escape(str(item.get("hakimin_adi", "")))
        status = escape(str(item.get("is_statusu", "")))
        date = escape(str(item.get("mehkeme_tarixi") or "-"))
        notes = escape(str(item.get("qeydler") or ""))
        note_line = f"\n  Qeyd: {notes}" if notes else ""
        lines.append(
            f"<b>/case{case_id} - {number}</b>\n"
            f"  Tərəf: {party}\n"
            f"  Məhkəmə: {court}\n"
            f"  Hakim: {judge}\n"
            f"  Status: {status} | Tarix: {date}{note_line}"
        )
    return "\n\n".join(lines)


def task_list(tasks: list[dict]) -> str:
    if not tasks:
        return "Tapşırıq yoxdur."

    lines: list[str] = []
    for item in tasks:
        task_id = escape(str(item.get("id", "")))
        raw_priority = item.get("prioritet")
        priority = TASK_PRIORITIES.get(int(0 if raw_priority is None else raw_priority), "Normal")
        status = TASK_STATUSES.get(str(item.get("veziyyet") or ""), str(item.get("veziyyet") or ""))
        date = str(item.get("son_tarix") or "-")
        time = str(item.get("son_tarix_saat") or "")
        deadline = escape((date + " " + time).strip())
        raw_content = str(item.get("mezmun") or "")
        content = escape(raw_content)
        content_lines = raw_content.splitlines()
        title = escape(str(item.get("basliq") or (content_lines[0] if content_lines else "Tapşırıq")))
        case_number = escape(str(item.get("is_nomresi") or "-"))
        party = escape(str(item.get("terefin_adi") or "-"))
        lines.append(
            f"<b>/task{task_id} - {priority} - {escape(status)}</b>\n"
            f"  İş: {case_number} | {party}\n"
            f"  Mahiyyət: {title}\n"
            f"  Tapşırıq: {content}\n"
            f"  Son tarix: {deadline}"
        )
    return "\n\n".join(lines)


def hearing_list(hearings: list[dict]) -> str:
    if not hearings:
        return "Yaxın iclas yoxdur."

    lines: list[str] = []
    for item in hearings:
        number = escape(str(item.get("is_nomresi") or "-"))
        party = escape(str(item.get("terefin_adi") or "-"))
        judge = escape(str(item.get("hakimin_adi") or "-"))
        date = escape(str(item.get("tarix") or "-"))
        time = escape(str(item.get("saat") or "-"))
        lines.append(f"<b>{date} {time}</b> - {number}\n  {party}\n  Hakim: {judge}")
    return "\n\n".join(lines)
