<?php
function getWeather(): ?array
{
    $cacheFile = CACHE_DIR . '/weather.json';

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < CACHE_TTL_WEATHER) {
        $cached = json_decode(file_get_contents($cacheFile), true);
        if ($cached) return $cached;
    }

    $params = http_build_query([
        'latitude'         => '49.94',
        'longitude'        => '-105.96',
        'current'          => 'temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m,wind_direction_10m',
        'daily'            => 'weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max',
        'temperature_unit' => 'celsius',
        'wind_speed_unit'  => 'kmh',
        'timezone'         => 'America/Regina',
        'forecast_days'    => '7',
    ]);

    $ctx = stream_context_create(['http' => ['method' => 'GET', 'timeout' => 8]]);
    $raw = @file_get_contents("https://api.open-meteo.com/v1/forecast?{$params}", false, $ctx);
    if (!$raw) return null;

    $j = json_decode($raw, true);
    if (!$j) return null;

    $wmo = [
        0  => ['Clear sky',              '☀️'],  1  => ['Mainly clear',           '🌤️'],
        2  => ['Partly cloudy',          '⛅'],  3  => ['Overcast',               '☁️'],
        45 => ['Foggy',                  '🌫️'],  48 => ['Icy fog',                '🌫️'],
        51 => ['Light drizzle',          '🌦️'],  53 => ['Drizzle',               '🌦️'],
        55 => ['Heavy drizzle',          '🌧️'],  61 => ['Light rain',             '🌧️'],
        63 => ['Rain',                   '🌧️'],  65 => ['Heavy rain',             '🌧️'],
        71 => ['Light snow',             '🌨️'],  73 => ['Snow',                   '❄️'],
        75 => ['Heavy snow',             '❄️'],  77 => ['Snow grains',            '🌨️'],
        80 => ['Light showers',          '🌦️'],  81 => ['Showers',               '🌧️'],
        82 => ['Heavy showers',          '🌧️'],  85 => ['Snow showers',           '🌨️'],
        86 => ['Heavy snow showers',     '❄️'],  95 => ['Thunderstorm',           '⛈️'],
        96 => ['Thunderstorm w/ hail',   '⛈️'],  99 => ['Thunderstorm w/ heavy hail', '⛈️'],
    ];

    $dirs = ['N','NE','E','SE','S','SW','W','NW'];
    $c    = $j['current'];
    $cWmo = $wmo[$c['weather_code']] ?? ['Unknown', '🌡️'];

    $forecast = [];
    foreach ($j['daily']['time'] as $i => $date) {
        $dw = $wmo[$j['daily']['weather_code'][$i]] ?? ['Unknown', '🌡️'];
        $forecast[] = [
            'date'                    => $date,
            'high'                    => (int)round($j['daily']['temperature_2m_max'][$i]),
            'low'                     => (int)round($j['daily']['temperature_2m_min'][$i]),
            'condition'               => $dw[0],
            'icon'                    => $dw[1],
            'precipitationProbability'=> (int)($j['daily']['precipitation_probability_max'][$i] ?? 0),
        ];
    }

    $data = [
        'location'      => 'Ardill, SK',
        'temperature'   => (int)round($c['temperature_2m']),
        'feelsLike'     => (int)round($c['apparent_temperature']),
        'humidity'      => $c['relative_humidity_2m'],
        'windSpeed'     => (int)round($c['wind_speed_10m']),
        'windDirection' => $dirs[(int)round($c['wind_direction_10m'] / 45) % 8],
        'condition'     => $cWmo[0],
        'icon'          => $cWmo[1],
        'observedAt'    => $c['time'],
        'forecast'      => $forecast,
    ];

    if (!is_dir(CACHE_DIR)) mkdir(CACHE_DIR, 0755, true);
    file_put_contents($cacheFile, json_encode($data));

    return $data;
}
