#!/usr/bin/env python3
"""Получение списка заявок из ServiceDesk Plus через API v3."""

import asyncio
import httpx
import json
import urllib3

BASE_URL = "https://192.168.1.237:8080"
API_TOKEN = "062CE056-C1F5-490C-A6DF-FD2C653A71DD"

async def list_tickets():
    url = f"{BASE_URL}/api/v3/requests"
    headers = {
        "authtoken": API_TOKEN,
        "Accept": "application/vnd.manageengine.sdp.v3+json"
    }
    
    params = {
        "input_data": json.dumps({
            "list_info": {
                "row_count": 50,
                "start_index": 1
            }
        })
    }
    
    async with httpx.AsyncClient(verify=False, timeout=30.0) as client:
        resp = await client.get(url, headers=headers, params=params)
        data = resp.json()
        
        requests = data.get("requests", [])
        print(f"Всего заявок: {len(requests)}\n")
        
        for req in requests:
            req_id = req.get("request_id", req.get("id", "?"))
            subject = req.get("subject", req.get("short_description", "?"))
            
            # Группа
            group = req.get("group", {})
            if isinstance(group, dict):
                group_name = group.get("name", "?")
            else:
                group_name = str(group)
            
            # Статус
            status = req.get("status", {})
            if isinstance(status, dict):
                status_name = status.get("name", "?")
            else:
                status_name = str(status)
            
            # Приоритет
            priority = req.get("priority", {})
            if isinstance(priority, dict):
                priority_name = priority.get("name", "?")
            else:
                priority_name = str(priority)
            
            # Описание (убираем HTML)
            desc = req.get("description", "")
            desc_clean = desc.replace("<p>", "").replace("</p>", "").replace("<br>", "\n").replace("<br/>", "\n").replace("<br />", "\n")
            desc_clean = desc_clean[:300]
            
            # Создатель
            requester = req.get("requester", {})
            req_name = requester.get("name", "?") if isinstance(requester, dict) else "?"
            
            print(f"--- Заявка #{req_id} ---")
            print(f"  Тема: {subject}")
            print(f"  Группа: {group_name}")
            print(f"  Статус: {status_name}")
            print(f"  Приоритет: {priority_name}")
            print(f"  Автор: {req_name}")
            print(f"  Описание:\n  {desc_clean}")
            print()

if __name__ == "__main__":
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    asyncio.run(list_tickets())
