"""Refresh the local snapshot explicitly, before starting the API server."""
import csv
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path

import requests

URL = 'https://archive-api.open-meteo.com/v1/archive'
# Stratford-upon-Avon, England. Replace these with your own town's coordinates.
LATITUDE = 52.19
LONGITUDE = -1.71
YEAR = 2025
COLUMNS = ['date', 'high_c', 'low_c', 'rain_mm']
BASE = Path(__file__).resolve().parent


def download():
    parameters = {'latitude': LATITUDE, 'longitude': LONGITUDE,
                  'start_date': f'{YEAR}-01-01', 'end_date': f'{YEAR}-12-31',
                  'daily': 'temperature_2m_max,temperature_2m_min,precipitation_sum',
                  'timezone': 'auto', 'format': 'csv'}
    response = requests.get(URL, params=parameters, timeout=30)
    response.raise_for_status()
    lines = response.content.decode('utf-8-sig').splitlines()
    # Open-Meteo describes the place in a few lines above the daily table.
    starts = [number for number, line in enumerate(lines) if line.startswith('time,')]
    if not starts:
        raise ValueError('The response is not the expected Open-Meteo CSV. Old snapshot kept.')
    # Read all rows before replacing a previous download.
    days = [day for day in csv.reader(lines[starts[0] + 1:]) if day]
    if not days or any(len(day) != len(COLUMNS) for day in days):
        raise ValueError('Incomplete CSV row. Old snapshot kept.')
    folder = BASE / 'data'
    folder.mkdir(exist_ok=True)
    snapshot = folder / 'weather.csv'
    with snapshot.open('w', encoding='utf-8', newline='') as target:
        writer = csv.writer(target, lineterminator='\n')
        writer.writerow(COLUMNS)
        writer.writerows(days)
    metadata = {'source_url': response.url,
                'retrieved_at': datetime.now(timezone.utc).isoformat(),
                'attribution': 'Weather data by Open-Meteo.com, offered under CC BY 4.0.',
                'notes': 'Location lines removed and columns renamed; values unchanged.',
                'sha256': hashlib.sha256(snapshot.read_bytes()).hexdigest()}
    snapshot.with_suffix('.csv.source.json').write_text(
        json.dumps(metadata, indent=2) + '\n', encoding='utf-8')
    print(f'Saved {len(days)} days to {snapshot}')


if __name__ == '__main__':
    download()
