from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import text
from ..database import get_db

router = APIRouter()

_VALID = {'LP92', 'EURO3', 'LAD', 'LADXM'}


@router.get('/tank-dip-charts/lookup')
def lookup_volume(
    tank_type: str = Query(...),
    height_cm: float = Query(..., ge=0),
    db: Session = Depends(get_db),
):
    if tank_type not in _VALID:
        raise HTTPException(status_code=400, detail=f'Invalid tank_type: {tank_type}')

    lower = db.execute(
        text(
            'SELECT height_cm, volume_ltr FROM tank_dip_charts '
            'WHERE tank_type = :t AND height_cm <= :h '
            'ORDER BY height_cm DESC LIMIT 1'
        ),
        {'t': tank_type, 'h': height_cm},
    ).fetchone()

    upper = db.execute(
        text(
            'SELECT height_cm, volume_ltr FROM tank_dip_charts '
            'WHERE tank_type = :t AND height_cm >= :h '
            'ORDER BY height_cm ASC LIMIT 1'
        ),
        {'t': tank_type, 'h': height_cm},
    ).fetchone()

    if lower is None and upper is None:
        return {'volume_ltr': 0.0}
    if lower is None:
        return {'volume_ltr': float(upper.volume_ltr)}
    if upper is None:
        return {'volume_ltr': float(lower.volume_ltr)}

    h0, v0 = float(lower.height_cm), float(lower.volume_ltr)
    h1, v1 = float(upper.height_cm), float(upper.volume_ltr)
    if h0 == h1:
        return {'volume_ltr': v0}

    volume = v0 + (v1 - v0) * (height_cm - h0) / (h1 - h0)
    return {'volume_ltr': round(volume, 2)}
