import asyncio
import httpx
from zammad_py import ZammadAPI
from .config import settings


def _client() -> ZammadAPI:
    return ZammadAPI(url=f"{settings.zammad_url.rstrip('/')}/api/v1", http_token=settings.zammad_token)


def _headers() -> dict:
    return {"Authorization": f"Token token={settings.zammad_token}"}


async def get_ticket(ticket_id: int) -> dict:
    return await asyncio.to_thread(lambda: _client().ticket.find(ticket_id))


async def get_agent_name() -> str:
    url = f"{settings.zammad_url.rstrip('/')}/api/v1/users/me"
    async with httpx.AsyncClient() as client:
        r = await client.get(url, headers=_headers())
        if r.status_code != 200:
            return ""
        data = r.json()
        return f"{data.get('firstname', '')} {data.get('lastname', '')}".strip()


async def get_customer_name(customer_id: int) -> str:
    url = f"{settings.zammad_url.rstrip('/')}/api/v1/users/{customer_id}"
    async with httpx.AsyncClient() as client:
        r = await client.get(url, headers=_headers())
        if r.status_code != 200:
            return ""
        data = r.json()
        return f"{data.get('firstname', '')} {data.get('lastname', '')}".strip()


async def get_customer_info(customer_id: int) -> dict:
    """Return name, email, and organization for a Zammad user."""
    url = f"{settings.zammad_url.rstrip('/')}/api/v1/users/{customer_id}"
    async with httpx.AsyncClient() as client:
        r = await client.get(url, headers=_headers())
        if r.status_code != 200:
            return {}
        data = r.json()
        name = f"{data.get('firstname', '')} {data.get('lastname', '')}".strip()
        return {
            "name": name,
            "email": data.get("email", ""),
            "organization": data.get("organization", ""),
        }


async def get_ticket_articles(ticket_id: int) -> list:
    url = f"{settings.zammad_url.rstrip('/')}/api/v1/ticket_articles/by_ticket/{ticket_id}"
    async with httpx.AsyncClient() as client:
        r = await client.get(url, headers=_headers())
        r.raise_for_status()
        return r.json()


async def post_comment(ticket_id: int, body: str, devops_url: str = "") -> dict:
    full_body = body
    if devops_url:
        full_body += f'<br><br><a href="{devops_url}">View in Azure DevOps →</a>'

    params = {
        "ticket_id": ticket_id,
        "body": full_body,
        "type": "note",
        "internal": False,
        "content_type": "text/html",
    }
    return await asyncio.to_thread(lambda: _client().ticket_article.create(params))
