"""Serve a saved Open-Meteo snapshot; page visits never download new data."""
import csv
import json
import math
from pathlib import Path

from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import FileResponse

BASE = Path(__file__).resolve().parent
SNAPSHOT = BASE / 'data' / 'weather.csv'
router = APIRouter()
LABELS = ['Below 0', '0 to <5', '5 to <10', '10 to <15',
          '15 to <20', '20 to <25', '25 to <30', '30 and above']


def summarize(rows, minimum):
    counts = [0] * len(LABELS)
    days = 0
    missing = 0
    for row in rows:
        days += 1
        try:
            high = float(row['high_c'])
        except (ValueError, TypeError):
            missing += 1
            continue
        if not math.isfinite(high):
            missing += 1
            continue
        if high < minimum:
            continue
        index = 0 if high < 0 else min(int(high // 5) + 1, 7)
        counts[index] += 1
    return {'minimum': minimum, 'days': days,
            'missing_highs': missing, 'selected': sum(counts),
            'labels': LABELS, 'counts': counts}


@router.get('/weather')
def weather(minimum: float = Query(default=20, ge=-60, le=60)):
    try:
        with SNAPSHOT.open(encoding='utf-8', newline='') as source:
            result = summarize(csv.DictReader(source), minimum)
        metadata = json.loads(SNAPSHOT.with_suffix('.csv.source.json').read_text())
    except (OSError, ValueError, KeyError, csv.Error):
        raise HTTPException(status_code=503,
                            detail='Snapshot unavailable. Run download_weather.py, then retry.') from None
    result['source'] = metadata
    return result


@router.get('/', include_in_schema=False)
def dashboard():
    return FileResponse(BASE / 'dashboard.html')
