from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
from utils.utils import get_db
from . import handler
from .schema import (
    CalculationinputCreate,
    CalculationinputResponse,
    CalculationDetailsResponse,
    CalculationWithResultAndChartResponse,
    PaginatedResponse,
)

router = APIRouter(prefix="/calculations", tags=["SIP Calculations"])


@router.post(
    "/",
    response_model=CalculationWithResultAndChartResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create New SIP Calculation",
    description="Creates a new SIP calculation with input parameters (monthly investment, expected return rate, time period). Validates inputs against business rules, applies SIP formula with monthly compounding, computes total investment, estimated returns, and maturity value, generates year-by-year chart data points, and returns the complete calculation with result and chart data immediately.",
)
def create_calculation_route(data: CalculationinputCreate, db: Session = Depends(get_db)):
    return handler.create_calculation_with_chart_data(db, data)


@router.get(
    "/{id}",
    response_model=CalculationinputResponse,
    summary="Retrieve Calculation Input by ID",
    description="Returns the calculation input record for the specified ID. Returns 404 if the calculation does not exist.",
)
def get_calculation_route(id: str, db: Session = Depends(get_db)):
    return handler.get_calculation_by_id(db, id)


@router.get(
    "/{id}/details",
    response_model=CalculationDetailsResponse,
    summary="Retrieve Calculation with Result and Chart Data",
    description="Returns the complete calculation including the input parameters, computed result (total investment, estimated returns, maturity value), and all year-by-year chart data points for visualization. Uses eager loading to efficiently fetch all related data in a single query. Returns 404 if the calculation does not exist.",
)
def get_calculation_details_route(id: str, db: Session = Depends(get_db)):
    return handler.get_calculation_details(db, id)


@router.get(
    "/",
    response_model=PaginatedResponse[CalculationinputResponse],
    summary="List All Calculations",
    description="Returns a paginated list of all calculation inputs. Supports optional filtering by timestamp range to find calculations performed within a specific time window. Results are ordered by creation timestamp descending (most recent first).",
)
def list_calculations_route(
    limit: int = Query(20, ge=1, le=100),
    offset: int = Query(0, ge=0),
    timestamp_start: Optional[datetime] = Query(None, description="Filter calculations from this timestamp (inclusive)"),
    timestamp_end: Optional[datetime] = Query(None, description="Filter calculations up to this timestamp (inclusive)"),
    db: Session = Depends(get_db),
):
    return handler.list_calculations(db, limit, offset, timestamp_start, timestamp_end)


@router.delete(
    "/{id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="Delete Calculation",
    description="Deletes the specified calculation input and all associated data (calculation result and chart data points) via cascade delete. Returns 404 if the calculation does not exist. This operation is permanent and cannot be undone.",
)
def delete_calculation_route(id: str, db: Session = Depends(get_db)):
    handler.delete_calculation(db, id)