"""Convert pycerebro tuples to dicts and utility functions."""

import datetime
import re

# ── Date conversion ──────────────────────────────────────────────────────────

_EPOCH = datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc)


def days_from_2000(iso_date: str) -> float:
    """ISO date string '2026-03-20' → days from 2000-01-01 as float."""
    dt = datetime.datetime.fromisoformat(iso_date).replace(tzinfo=datetime.timezone.utc)
    return (dt - _EPOCH).total_seconds() / 86400.0


def days_to_iso(days: float | None) -> str | None:
    """Days from 2000-01-01 → ISO date string, or None."""
    if days is None or days == 0:
        return None
    dt = _EPOCH + datetime.timedelta(days=days)
    return dt.strftime("%Y-%m-%d")


# ── HTML cleanup ─────────────────────────────────────────────────────────────

_TAG_RE = re.compile(r"<[^>]+>")


def html_to_text(html: str | None) -> str:
    """Strip HTML tags, decode basic entities."""
    if not html:
        return ""
    text = html.replace("<br>", "\n").replace("<br/>", "\n").replace("<br />", "\n")
    text = text.replace("&nbsp;", " ").replace("&amp;", "&")
    text = text.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"')
    return _TAG_RE.sub("", text).strip()


# ── Task ─────────────────────────────────────────────────────────────────────

def task_to_dict(t) -> dict:
    return {
        "id": str(t[1]),
        "parent_id": str(t[2]),
        "name": t[4],
        "parent_url": t[5],
        "activity_name": t[6],
        "activity_id": str(t[7]),
        "created": str(t[10]) if t[10] else None,
        "priority": t[11],
        "progress": t[12],
        "planned_hours": t[13],
        "flags": t[17],
        "allocated": t[21],
        "start": days_to_iso(t[26]),
        "finish": days_to_iso(t[27]),
        "budget": t[28],
        "status_id": str(t[36]) if t[36] is not None else None,
        "cc_status": t[37],
        "order": t[39] if len(t) > 39 else None,
    }


# ── Message ──────────────────────────────────────────────────────────────────

_MSG_TYPES = {
    0: "definition",
    1: "review",
    2: "report",
    3: "note",
    4: "client_review",
    5: "resource_report",
    6: "status_change",
}


def message_to_dict(m) -> dict:
    return {
        "id": str(m[1]),
        "parent_id": str(m[2]),
        "type": m[3],
        "type_name": _MSG_TYPES.get(m[3], str(m[3])),
        "creator_name": m[4],
        "created": str(m[5]) if m[5] else None,
        "work_time_minutes": m[6],
        "text_html": m[7],
        "text": html_to_text(m[7]),
        "flags": m[9],
        "task_id": str(m[11]),
        "creator_id": str(m[13]),
        "status_id": str(m[15]) if len(m) > 15 and m[15] is not None else None,
    }


# ── User ─────────────────────────────────────────────────────────────────────

def user_to_dict(u) -> dict:
    return {
        "id": str(u[0]),
        "full_name": u[1],
        "flags": u[2],
        "login": u[3],
        "first_name": u[4],
        "last_name": u[5],
        "email": u[6],
        "phone": u[7] if len(u) > 7 else None,
    }


# ── Attachment ───────────────────────────────────────────────────────────────

_ATT_TAGS = {
    0: "file",
    1: "thumb1",
    2: "thumb2",
    3: "thumb3",
    4: "review",
    5: "link",
}

_VIDEO_EXTS = {".mov", ".mp4", ".avi", ".mkv", ".wmv", ".flv", ".webm", ".m4v", ".mpg", ".mpeg"}


def attachment_to_dict(a) -> dict:
    return {
        "id": str(a[10]),
        "message_id": str(a[1]),
        "deleted": a[2] != 0,
        "group_id": str(a[3]),
        "created": str(a[4]) if a[4] else None,
        "hash": a[5],
        "tag": a[6],
        "tag_name": _ATT_TAGS.get(a[6], str(a[6])),
        "file_size": a[7],
        "file_name": a[8],
        "comment": a[9],
    }


def is_video_attachment(attachments_group: list[dict]) -> bool:
    """Check if attachment group represents a video (has thumb2/thumb3 or video extension)."""
    tags = {a["tag"] for a in attachments_group}
    if 2 in tags or 3 in tags:
        return True
    for a in attachments_group:
        if a["tag"] == 0 and a.get("file_name"):
            ext = "." + a["file_name"].rsplit(".", 1)[-1].lower() if "." in a["file_name"] else ""
            if ext in _VIDEO_EXTS:
                return True
    return False


# ── Status ───────────────────────────────────────────────────────────────────

def status_to_dict(s) -> dict:
    return {
        "id": str(s[0]),
        "name": s[1],
        "flags": s[2],
        "order": s[3],
        "description": s[4],
        "color": s[6],
    }


# ── Activity ─────────────────────────────────────────────────────────────────

def activity_to_dict(a) -> dict:
    return {
        "id": str(a[0]),
        "name": a[1],
        "color": a[2],
    }


# ── Tag ──────────────────────────────────────────────────────────────────────

_TAG_TYPES = {
    0: "integer",
    1: "enum",
    2: "float",
    3: "string",
    4: "multi_enum",
    5: "user",
    6: "multi_user",
}


def tag_to_dict(t) -> dict:
    return {
        "id": str(t[1]),
        "project_id": str(t[2]),
        "name": t[3],
        "type": t[4],
        "type_name": _TAG_TYPES.get(t[4], str(t[4])),
    }


def task_tag_to_dict(t) -> dict:
    return {
        "task_id": str(t[0]),
        "tag_id": str(t[1]),
        "type": t[2],
        "name": t[3],
        "value": t[4],
    }


def check_to_dict(c) -> dict:
    return {
        "check_id": str(c[3]),
        "task_id": str(c[2]),
        "value": c[5],
        "order": c[6] if len(c) > 6 else None,
        "flags": c[4],
    }
