from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Dict, Optional
from datetime import date

from app.services.currency_service import currency_service

router = APIRouter()

@router.get("/rates")
async def get_exchange_rates(base: str = "USD"):
    """Get current exchange rates for a base currency"""
    try:
        supported_currencies = currency_service.get_supported_currencies()
        rates = {}

        for currency_code in supported_currencies.keys():
            if currency_code != base:
                rate = currency_service.get_exchange_rate(base, currency_code)
                if rate:
                    rates[currency_code] = rate

        return {
            "base": base,
            "date": date.today().isoformat(),
            "rates": rates
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/convert")
async def convert_currency(
    amount: float,
    from_currency: str,
    to_currency: str,
    historical_date: Optional[str] = None
):
    """Convert amount from one currency to another"""
    try:
        if amount <= 0:
            raise HTTPException(status_code=400, detail="Amount must be greater than 0")

        # Parse historical date if provided
        hist_date = None
        if historical_date:
            try:
                hist_date = date.fromisoformat(historical_date)
            except ValueError:
                raise HTTPException(status_code=400, detail="Invalid date format. Use YYYY-MM-DD")

        converted_amount = currency_service.convert_amount(amount, from_currency, to_currency)
        rate = currency_service.get_exchange_rate(from_currency, to_currency)

        return {
            "amount": amount,
            "from_currency": from_currency,
            "to_currency": to_currency,
            "converted_amount": round(converted_amount, 2),
            "exchange_rate": rate,
            "date": historical_date or date.today().isoformat()
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/supported")
async def get_supported_currencies():
    """Get list of supported currencies"""
    try:
        currencies = currency_service.get_supported_currencies()
        return {
            "currencies": currencies,
            "count": len(currencies)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/format")
async def format_currency(amount: float, currency_code: str):
    """Format amount with appropriate currency symbol"""
    try:
        formatted = currency_service.format_currency(amount, currency_code)
        return {
            "amount": amount,
            "currency_code": currency_code,
            "formatted": formatted
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

class BatchConvertRequest(BaseModel):
    conversions: list[Dict[str, float | str]]  # Each dict should have 'amount', 'from_currency', 'to_currency'

@router.post("/batch-convert")
async def batch_convert_currencies(request: BatchConvertRequest):
    """Convert multiple amounts in a single request"""
    try:
        results = []

        for conversion in request.conversions:
            amount = conversion.get('amount', 0)
            from_currency = conversion.get('from_currency', '')
            to_currency = conversion.get('to_currency', '')

            if amount <= 0 or not from_currency or not to_currency:
                results.append({
                    "error": "Invalid conversion data",
                    "amount": amount,
                    "from_currency": from_currency,
                    "to_currency": to_currency
                })
                continue

            converted_amount = currency_service.convert_amount(amount, from_currency, to_currency)
            rate = currency_service.get_exchange_rate(from_currency, to_currency)

            results.append({
                "amount": amount,
                "from_currency": from_currency,
                "to_currency": to_currency,
                "converted_amount": round(converted_amount, 2),
                "exchange_rate": rate
            })

        return {
            "conversions": results,
            "count": len(results)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))