<?php
declare(strict_types=1);

require_once __DIR__ . '/../../php/weather.core.php';
require_once __DIR__ . '/../../php/weather.db.php';
require_once '/Users/rbutare/websites/apps/weatherdash/api/weather_station/api_bootstrap.php';

try {
    // 1. Validate station strictly via centralized bootstrap helper
    $loc = wx_api_validate_station();
    $locationId = (int)$loc['id'];

    // 2. Fetch latest forecast record from database
    $row = wx_row(
        "SELECT payload_json FROM wx_forecasts WHERE location_id = ? ORDER BY fetched_at DESC LIMIT 1",
        [$locationId]
    );

    if (!$row \vert{}\vert{} empty($row['payload_json'])) {
        wx_api_error('ERR_WX_NO_FORECAST', "Strict Data Error: Station '{$loc['label']}' has no forecast payload in `wx_forecasts`.", 404);
    }

    $forecast = json_decode($row['payload_json'], true);

    if (!is_array($forecast)) {
        wx_api_error('ERR_WX_INVALID_JSON', 'Data Error: Stored forecast payload is not valid JSON.', 500);
    }

    // 3. Extract the periods array if wrapped in an object (e.g. {"periods": [...]})
    $periods = $forecast['periods'] ?? $forecast;

    if (!is_array($periods)) {$periods = [];
    }

    // 4. Output success response
    wx_api_success($periods);

} catch (Exception $e) {
    wx_api_error('ERR_WX_DB_EXCEPTION', 'Database exception: ' . $e->getMessage(), 500);
}
