"""Shared AwoooP operator deeplinks used by Telegram-facing services."""

from urllib.parse import quote
from urllib.parse import urlencode

AWOOOP_WEB_BASE_URL = "https://awoooi.wooo.work"


def incident_runs_url(
    incident_id: str,
    *,
    project_id: str = "awoooi",
    locale: str = "zh-TW",
) -> str:
    safe_project_id = quote(str(project_id or "awoooi"), safe="")
    safe_incident_id = quote(str(incident_id or ""), safe="")
    return (
        f"{AWOOOP_WEB_BASE_URL}/{locale}/awooop/runs"
        f"?project_id={safe_project_id}&incident_id={safe_incident_id}"
    )


def incident_alerts_url(
    incident_id: str,
    *,
    project_id: str = "awoooi",
    locale: str = "zh-TW",
) -> str:
    safe_project_id = quote(str(project_id or "awoooi"), safe="")
    safe_incident_id = quote(str(incident_id or ""), safe="")
    return (
        f"{AWOOOP_WEB_BASE_URL}/{locale}/alerts"
        f"?project_id={safe_project_id}&incident_id={safe_incident_id}"
    )


def incident_truth_chain_button_row(
    incident_id: str,
    *,
    project_id: str = "awoooi",
) -> list[dict[str, str]]:
    if not incident_id:
        return []
    return [
        {
            "text": "🔎 真相鏈",
            "url": incident_alerts_url(incident_id, project_id=project_id),
        },
        {
            "text": "🧭 Runs",
            "url": incident_runs_url(incident_id, project_id=project_id),
        },
    ]


def incident_truth_chain_reply_markup(
    incident_id: str,
    *,
    project_id: str = "awoooi",
) -> dict | None:
    row = incident_truth_chain_button_row(incident_id, project_id=project_id)
    if not row:
        return None
    return {"inline_keyboard": [row]}


def work_item_url(
    work_item_id: str,
    *,
    incident_id: str = "",
    project_id: str = "awoooi",
    locale: str = "zh-TW",
) -> str:
    params = {
        "project_id": str(project_id or "awoooi"),
        "work_item_id": str(work_item_id or ""),
    }
    if incident_id:
        params["incident_id"] = str(incident_id)
    return f"{AWOOOP_WEB_BASE_URL}/{locale}/awooop/work-items?{urlencode(params)}"
