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

import requests

URL = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.csv'
BASE = Path(__file__).resolve().parent


def download():
    response = requests.get(URL, timeout=30)
    response.raise_for_status()
    content = response.content
    rows = csv.DictReader(io.StringIO(content.decode('utf-8-sig')))
    if not {'mag', 'type'}.issubset(rows.fieldnames or []):
        raise ValueError('The response is not the expected USGS CSV. Old snapshot kept.')
    # Read all rows before replacing a previous download.
    records = list(rows)
    if any(row['type'] is None or row['mag'] is None for row in records):
        raise ValueError('Incomplete CSV row. Old snapshot kept.')
    metadata = {'source_url': URL,
                'retrieved_at': datetime.now(timezone.utc).isoformat(),
                'attribution': 'U.S. Geological Survey Earthquake Hazards Program.',
                'sha256': hashlib.sha256(content).hexdigest()}
    folder = BASE / 'data'
    folder.mkdir(exist_ok=True)
    snapshot = folder / 'earthquakes.csv'
    snapshot.write_bytes(content)
    snapshot.with_suffix('.csv.source.json').write_text(
        json.dumps(metadata, indent=2) + '\n', encoding='utf-8')
    print(f'Saved {len(records)} events to {snapshot}')


if __name__ == '__main__':
    download()
