import json

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from schemas.country import ResponseCity, ResponseCountry
from services.country import get_cities_by_country, get_countrie_all
from fastapi import APIRouter, Depends, HTTPException
from database import get_db
from sqlalchemy.orm import Session

router = APIRouter()

@router.get("/financials/mobiles/countries", response_model=list[ResponseCountry])
def get_country(db: Session = Depends(get_db)):
    countries = get_countrie_all(db)
    if not countries:
        raise HTTPException(status_code=404, detail="Country not found")

    # ✅ Conversion SQLAlchemy -> dictionnaire
    result = [
        {
            "id": c.id,
            "name": c.name,
            "code": c.code,
            "currency": getattr(c, "currency", None),
        }
        for c in countries
    ]

    # ✅ JSON UTF-8 correct (préserve les accents)
    json_data = json.dumps(result, ensure_ascii=False)

    # ✅ On envoie explicitement le header charset=utf-8
    return JSONResponse(
        content=json.loads(json_data),
        media_type="application/json; charset=utf-8"
    )


@router.get("/financials/cities/country/details/{country_id}")
def get_cities(country_id: str, db: Session = Depends(get_db)):
    cities = get_cities_by_country(db, country_id)
    if not cities:
        raise HTTPException(status_code=404, detail="No cities found for this country")
    
    # ✅ Convertit les objets SQLAlchemy / datetime / enum en JSON valide
    json_data = jsonable_encoder(cities)

    return JSONResponse(
        content=json_data,
        media_type="application/json; charset=utf-8"
    )
