import httpx
import asyncio
from app.core import config
from app.core.logger import logger, log_async
from urllib.parse import urlencode
import re

paises = [
    {"id": 40, "nombre": "Chile"},
    {"id": 36, "nombre": "Mexico"},
    {"id": 45, "nombre": "Peru"},
]

async def crear_elemento(token: str, code: str, address: str, url_streming: str,country:str):
    url = f"{config.API_FRONT_BASE_URL}/elements"
    country_id =obtener_id_por_nombre(country)
    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {token}",
    }
    if url_streming:
        data = {
            'data[attributes][name]': code,
            'data[attributes][code]': code,
            'data[attributes][description]': address,
            'data[attributes][address]': address,
            'data[attributes][url]': url_streming,
            'data[attributes][country_id]': country_id,
        }
    else:
        data = {
            'data[attributes][name]': code,
            'data[attributes][code]': code,
            'data[attributes][description]': address,
            'data[attributes][address]': address,
            'data[attributes][country_id]': country_id,
        }
    async with httpx.AsyncClient(timeout=30.0) as client:
        try:
            response = await client.post(url, headers=headers, data=data)
            #response.raise_for_status()
            return response
        except httpx.HTTPStatusError as e:
            logger.info("Response body:", e.response.text)
            print("❌ Error HTTP")
            print("Status:", e.response.status_code)
            print("URL:", e.request.url)
            print("Response headers:", e.response.headers)
            print("Response body:", e.response.text)
            #raise
        
async def update_element(token: str, data: list[str],code:str):
    url = f"{config.API_FRONT_BASE_URL}/elements/campaigns/{code}"

    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/x-www-form-urlencoded",
    }
    result = []
    for val in data.campaings:
        match = re.match(r'^(OS\d+)_', val)
        if match:
            result.append(match.group(1))
        else:
            result.append(val)

    data = {
        'lang': 'es',
        'data[campaigns][]': result,  # ← lista pasada por parámetro
    }

    encoded_data = urlencode(data, doseq=True)  # importante para repetir []

    async with httpx.AsyncClient(timeout=30.0) as client:
        try:
            response = await client.put(url, headers=headers, content=encoded_data)
            #response.raise_for_status()
            return response
        except httpx.HTTPStatusError as e:
            print("❌ Error HTTP")
            print("Status:", e.response.status_code)
            print("URL:", e.request.url)
            print("Response headers:", e.response.headers)
            print("Response body:", e.response.text)
            #raise
             
def obtener_id_por_nombre(nombre: str):
    for pais in paises:
        if pais["nombre"].lower() == nombre.lower():
            return pais["id"]
    return None

def crear_elemento_def(token: str, code: str, address: str, url_streaming: str, country: str):
    url = f"{config.API_FRONT_BASE_URL}/elements"
    country_id = obtener_id_por_nombre(country)
    headers = {"Accept": "application/json", "Authorization": f"Bearer {token}"}

    data = {
        'data[attributes][name]': code,
        'data[attributes][code]': code,
        'data[attributes][description]': address,
        'data[attributes][address]': address,
        'data[attributes][country_id]': country_id,
    }

    if url_streaming:
        data['data[attributes][url]'] = url_streaming

    try:
        with httpx.Client(timeout=30.0) as client:  # versión síncrona
            response = client.post(url, headers=headers, data=data)
            #response.raise_for_status()
            return response
    except httpx.HTTPStatusError as e:
        print("❌ Error HTTP")
        print("Status:", e.response.status_code)
        print("URL:", e.request.url)
        print("Response body:", e.response.text)
        #raise