from typing import List, Optional
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from core.database import get_core_db
from core.security import get_current_user
from .service import HistoricalTariffFractionService
from .schemas import HistoricalTariffFractionResponse, HistoricalTariffFractionCreate, HistoricalTariffFractionUpdate, HistoricalTariffFractionListResponse

from api.v1.common.tenant_crud_routes import validate_access_to_resource

router = APIRouter()

@router.get("/", response_model=HistoricalTariffFractionListResponse)
def get_historical_fractions(
    company_id: int = Query(..., description="Company ID"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=1000, description="Page size"),
    historical_fraction: Optional[str] = Query(None, description="Search by historical fraction code"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["frac_historical.view"]
    )
    skip = (page - 1) * page_size
    service = HistoricalTariffFractionService(db)
    items, total = service.get_multi(tenant_id, company_id, skip=skip, limit=page_size, historical_fraction=historical_fraction)
    return {
        "items": items,
        "total": total,
        "page": page,
        "page_size": page_size,
        "pages": (total + page_size - 1) // page_size if page_size > 0 else 1
    }

@router.get("/rate")
async def get_rate(
    company_id: int = Query(..., description="Company ID"),
    historical_fraction: str = Query(..., description="8-character fraction code"),
    nico: str = Query(..., description="2-character NICO code"),
    direction: str = Query("export", description="Movement direction: 'import' or 'export'"),
    tariff_type: str = Query("GENERAL", description="Tariff regimen: 'GENERAL', 'PROSEC', etc."),
    invoice_date: str = Query(..., description="ISO Date (YYYY-MM-DD)"),
    is_regime_change: bool = Query(False, description="Whether the invoice is a regime change (Cambio de Régimen)"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["frac_historical.view"]
    )
    
    # Parse date
    try:
        parsed_date = datetime.fromisoformat(invoice_date.split('T')[0])
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid date format. Use YYYY-MM-DD")

    service = HistoricalTariffFractionService(db)
    rate = await service.get_historical_rate(
        tenant_id=int(tenant_id),
        company_id=company_id,
        historical_fraction=historical_fraction,
        nico=nico,
        direction=direction,
        tariff_type=tariff_type,
        invoice_date=parsed_date,
        is_regime_change=is_regime_change
    )
    
    if rate is None:
        return {"found": False, "rate": 0}
        
    return {"found": True, "rate": float(rate)}

@router.get("/{id}", response_model=HistoricalTariffFractionResponse)
def get_historical_fraction(
    id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["frac_historical.view"]
    )
    service = HistoricalTariffFractionService(db)
    fraction = service.get(id, tenant_id, company_id)
    if not fraction:
        raise HTTPException(status_code=404, detail="Historical tariff fraction not found")
    return fraction

@router.post("/", response_model=HistoricalTariffFractionResponse)
def create_historical_fraction(
    fraction_in: HistoricalTariffFractionCreate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["frac_historical.create"]
    )
    service = HistoricalTariffFractionService(db)
    return service.create(fraction_in, tenant_id, company_id)

@router.put("/{id}", response_model=HistoricalTariffFractionResponse)
def update_historical_fraction(
    id: int,
    fraction_in: HistoricalTariffFractionUpdate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["frac_historical.edit"]
    )
    service = HistoricalTariffFractionService(db)
    fraction = service.get(id, tenant_id, company_id)
    if not fraction:
        raise HTTPException(status_code=404, detail="Historical tariff fraction not found")
    return service.update(fraction, fraction_in)

@router.delete("/{id}", response_model=HistoricalTariffFractionResponse)
def delete_historical_fraction(
    id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["frac_historical.delete"]
    )
    service = HistoricalTariffFractionService(db)
    fraction = service.get(id, tenant_id, company_id)
    if not fraction:
        raise HTTPException(status_code=404, detail="Historical tariff fraction not found")
    return service.delete(id, tenant_id, company_id)
