#!/usr/bin/env python3
"""Поиск рабочего формата фильтрации."""

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 test_filters():
    url = f"{BASE_URL}/api/v3/requests"
    headers = {
        "authtoken": API_TOKEN,
        "Accept": "application/vnd.manageengine.sdp.v3+json"
    }
    
    # Сначала посмотрим все заявки с их ID и датами
    print("=== Все заявки ===")
    async with httpx.AsyncClient(verify=False, timeout=30.0) as client:
        resp = await client.get(url, headers=headers, params={
            "input_data": json.dumps({
                "list_info": {"row_count": 100, "start_index": 1}
            })
        })
        data = resp.json()
        requests = data.get("requests", [])
        
        for req in requests:
            req_id = req.get("request_id", req.get("id", "?"))
            subject = req.get("subject", "?")
            created = req.get("created_time", {})
            if isinstance(created, dict):
                created_str = created.get("display_value", "?")
                ts = created.get("value", "?")
            else:
                created_str = str(created)
                ts = "?"
            print(f"  ID={req_id} created={created_str} ts={ts}")
        
        # Попробуем разные форматы фильтрации
        print("\n=== Попробуем фильтры ===")
        
        filters = [
            # Вариант 1: ISO строка
            {
                "search_criteria": {
                    "column_name": "created_time",
                    "condition": "between",
                    "values": ["Jul 1, 2026 00:00:00", "Jul 31, 2026 23:59:59"]
                }
            },
            # Вариант 2: без search_criteria, с custom_field
            {
                "search_criteria": {
                    "column_name": "created_time",
                    "condition": "between",
                    "values": ["2026-07-01", "2026-07-31"]
                }
            },
            # Вариант 3: timestamp как строка
            {
                "search_criteria": {
                    "column_name": "created_time",
                    "condition": "between",
                    "values": ["1782864000000", "1785542399000"]
                }
            },
        ]
        
        for i, criteria in enumerate(filters):
            params = {
                "input_data": json.dumps({
                    "list_info": {"row_count": 100, "start_index": 1},
                    "search_criteria": criteria.get("search_criteria")
                })
            }
            resp = await client.get(url, headers=headers, params=params)
            data = resp.json()
            reqs = data.get("requests", [])
            print(f"\nФильтр {i+1}: {criteria['search_criteria']['values']} -> {len(reqs)} заявок")
            for r in reqs:
                print(f"  {r.get('id')}: {r.get('subject')}")

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