<?php
/**
 * Traffic Cameras API — OHGO Cincinnati cameras
 * Returns downtown/bridge/Hopple area cameras with live image URLs.
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$cacheFile = __DIR__ . '/../uploads/cameras_cache.json';
$cacheTTL = 120; // 2 minutes

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTTL) {
    header('Content-Type: application/json');
    readfile($cacheFile);
    exit;
}

$apiKey = OHGO_API_KEY;
if (empty($apiKey)) {
    jsonResponse(['error' => 'OHGO API key not configured'], 500);
}

$url = "https://publicapi.ohgo.com/api/v1/cameras?region=Cincinnati";
$ctx = stream_context_create(['http' => [
    'timeout' => 10,
    'ignore_errors' => true,
    'header' => "Authorization: APIKEY {$apiKey}\r\nAccept: application/json\r\n"
]]);

$response = @file_get_contents($url, false, $ctx);
if ($response === false) {
    if (file_exists($cacheFile)) {
        header('Content-Type: application/json');
        readfile($cacheFile);
        exit;
    }
    jsonResponse(['error' => 'Unable to fetch camera data'], 502);
}

$data = json_decode($response, true);
if (!$data || !isset($data['results'])) {
    jsonResponse(['error' => 'Invalid camera data'], 502);
}

// Curated camera IDs for downtown Cincinnati, bridges, and Hopple St area
$curatedIds = [
    // Brent Spence Bridge / I-75 downtown
    '00000000000790' => 'I-75 at 3rd St',
    '00000000000789' => 'I-75 at 6th St',
    '00000000000791' => 'I-71/I-75 Merge',
    '00000000000431' => 'I-75 at Linn St',
    '00000000000788' => 'I-75 at Ezzard Charles Dr',
    // Hopple St area
    '00000000000786' => 'I-75 at Hopple St',
    '00000000000095' => 'I-75 North of Hopple St',
    '00000000000539' => 'I-75 South of Hopple St',
    // Western Hills Viaduct
    '00000000000787' => 'I-75 at Western Hills Viaduct',
    '00000000000799' => 'I-75 at I-74',
    '00000000000317' => 'I-75 South of I-74',
    // Downtown city cameras
    '00000000001260' => '3rd St at Vine St',
    '00000000001261' => '2nd St at Elm St',
    '00000000001263' => '3rd St at Sycamore St',
    '00000000001264' => 'Eggleston Ave at Pete Rose Way',
    // I-71 downtown
    '00000000000798' => 'I-71 at US-50 (Lytle Tunnel)',
    '00000000000793' => 'I-71 at I-471',
    '00000000000574' => 'I-71 at Casino/Gilbert Ave',
];

$cameras = [];
foreach ($data['results'] as $cam) {
    $id = $cam['id'] ?? '';
    if (!isset($curatedIds[$id])) continue;

    $views = $cam['cameraViews'] ?? [];
    $imageUrl = $views[0]['largeUrl'] ?? '';

    $cameras[] = [
        'id'          => $id,
        'name'        => $curatedIds[$id],
        'description' => $cam['description'] ?? '',
        'latitude'    => $cam['latitude'] ?? 0,
        'longitude'   => $cam['longitude'] ?? 0,
        'image_url'   => $imageUrl,
    ];
}

$result = [
    'cameras'    => $cameras,
    'count'      => count($cameras),
    'updated_at' => date('c'),
];

@file_put_contents($cacheFile, json_encode($result));
jsonResponse($result);
