"""Fuel-stop logging for B2B (fleet) truck drivers — a driver records a
fuel stop (station, amount spent, liters, odometer, an optional receipt
photo/PDF, an optional one-tap current-location capture) and their fleet
company can see the history and simple running totals per truck/driver.
Deliberately plain sums, not a full analytics/reporting engine — matches
the scope actually asked for."""

from decimal import Decimal

from accounts.supabase_client import get_client


def create_fuel_log(picker_id, company_id, truck_id=None, station_name='', amount_spent=None,
                     liters=None, odometer_km=None, lat=None, lng=None, receipt_url=None, notes=''):
    row = {
        'picker_id': picker_id,
        'company_id': company_id,
        'truck_id': truck_id,
        'station_name': station_name.strip() if station_name else None,
        'amount_spent': str(amount_spent) if amount_spent is not None else None,
        'liters': str(liters) if liters is not None else None,
        'odometer_km': str(odometer_km) if odometer_km is not None else None,
        'lat': lat,
        'lng': lng,
        'receipt_url': receipt_url,
        'notes': notes.strip() if notes else None,
    }
    resp = get_client().table('pickker_fuel_logs').insert(row).execute()
    return resp.data[0] if resp.data else None


def get_fuel_logs_for_company(company_id, truck_id=None, picker_id=None, limit=100):
    query = get_client().table('pickker_fuel_logs').select('*').eq('company_id', company_id)
    if truck_id:
        query = query.eq('truck_id', truck_id)
    if picker_id:
        query = query.eq('picker_id', picker_id)
    return query.order('created_at', desc=True).limit(limit).execute().data


def get_fuel_logs_for_driver(picker_id, limit=50):
    return (
        get_client().table('pickker_fuel_logs').select('*')
        .eq('picker_id', picker_id).order('created_at', desc=True).limit(limit).execute().data
    )


def get_fuel_summary_for_company(company_id):
    """Plain totals — overall, and broken down per truck. No trend/chart
    computation; that's more than was actually asked for."""
    rows = get_client().table('pickker_fuel_logs').select('*').eq('company_id', company_id).execute().data

    def _dec(v):
        return Decimal(str(v)) if v is not None else Decimal('0')

    total_spent = sum((_dec(r['amount_spent']) for r in rows), Decimal('0'))
    total_liters = sum((_dec(r['liters']) for r in rows), Decimal('0'))

    by_truck = {}
    for r in rows:
        key = r.get('truck_id')
        entry = by_truck.setdefault(key, {'truck_id': key, 'spent': Decimal('0'), 'liters': Decimal('0'), 'count': 0})
        entry['spent'] += _dec(r['amount_spent'])
        entry['liters'] += _dec(r['liters'])
        entry['count'] += 1

    return {
        'total_spent': total_spent,
        'total_liters': total_liters,
        'entry_count': len(rows),
        'by_truck': list(by_truck.values()),
    }
