import os

import httpx
from typing import List


async def fetch_new_post_zones() -> List[dict]:
    url = "https://api.novaposhta.ua/v2.0/json/"
    api_key = os.getenv("NOVAPOSHTA_KEY")
    
    if not api_key:
        raise Exception("NOVAPOSHTA_KEY environment variable is not set")

    payload = {
        "apiKey": api_key,
        "modelName": "Address",
        "calledMethod": "getAreas",
        "methodProperties": {}
    }

    async with httpx.AsyncClient(timeout=10) as client:
        response = await client.post(url, json=payload)
        response.raise_for_status()
        data = response.json()

    # Перевірка структури відповіді
    if not data.get("success"):
        raise Exception(f"Nova Poshta API error: {data.get('errors')}")

    areas = data.get("data", [])
    # Повертаємо список словників із назвою області
    return [{"name": area.get("Description")} for area in areas if area.get("Description")]


async def fetch_new_post_cities() -> List[dict]:
    url = "https://api.novaposhta.ua/v2.0/json/"
    api_key = os.getenv("NOVAPOSHTA_KEY")
    
    if not api_key:
        raise Exception("NOVAPOSHTA_KEY environment variable is not set")

    payload = {
        "apiKey": api_key,
        "modelName": "Address",
        "calledMethod": "getCities",
        "methodProperties": {}
    }

    async with httpx.AsyncClient(timeout=10) as client:
        response = await client.post(url, json=payload)
        response.raise_for_status()
        data = response.json()

    if not data.get("success"):
        raise Exception(f"Nova Poshta API error: {data.get('errors')}")

    cities = data.get("data", [])
    return [
        {
            "name": city.get("Description"),
            "zone_name": city.get("AreaDescription")  # <<< Ось тут зміна!
        }
        for city in cities if city.get("Description") and city.get("AreaDescription")
    ]

async def fetch_zone_ref_by_name(zone_name: str) -> str:
    url = "https://api.novaposhta.ua/v2.0/json/"
    api_key = os.getenv("NOVAPOSHTA_KEY")
    
    if not api_key:
        raise Exception("NOVAPOSHTA_KEY environment variable is not set")

    payload = {
        "apiKey": api_key,
        "modelName": "Address",
        "calledMethod": "getAreas",
        "methodProperties": {}
    }

    async with httpx.AsyncClient(timeout=10) as client:
        response = await client.post(url, json=payload)
        response.raise_for_status()
        data = response.json()

    if not data.get("success"):
        raise Exception(f"Nova Poshta API error: {data.get('errors')}")

    for area in data.get("data", []):
        if area.get("Description", "").strip().lower() == zone_name.strip().lower():
            return area.get("Ref")

    raise ValueError(f"Zone '{zone_name}' not found in Nova Poshta API.")


async def get_zone_ref_by_name(zone_name: str) -> str:
    zones = await fetch_new_post_zones()
    for zone in zones:
        name = zone.get("name")
        if name and name.strip().lower() == zone_name.strip().lower():
            # Використовуємо правильну функцію
            return await fetch_zone_ref_by_name(zone_name)
    raise ValueError(f"Zone '{zone_name}' not found in Nova Poshta API.")


async def fetch_np_cities_for_zone(zone_ref: str) -> List[dict]:
    url = "https://api.novaposhta.ua/v2.0/json/"
    api_key = os.getenv("NOVAPOSHTA_KEY")
    
    if not api_key:
        raise Exception("NOVAPOSHTA_KEY environment variable is not set")

    payload = {
        "apiKey": api_key,
        "modelName": "Address",
        "calledMethod": "getCities",
        "methodProperties": {
            "Area": zone_ref
        }
    }

    async with httpx.AsyncClient(timeout=10) as client:
        response = await client.post(url, json=payload)
        response.raise_for_status()
        data = response.json()

    if not data.get("success"):
        raise Exception(f"Nova Poshta API error: {data.get('errors')}")

    # Повертаємо і назву міста, і назву області (для area_text)
    return [
        {
            "name": city.get("Description"),
            "area_text": city.get("AreaDescription")
        }
        for city in data.get("data", [])
        if city.get("Description")
    ]

