<?php
/**
 * Cron: Snowflake Data Sync
 * Calls the Python Snowflake sync script on the NAS.
 * Run: php cron/sync-snowflake.php (daily via crontab)
 * Crontab: 0 2 * * * cd /path/to/cincinnatifire && php cron/sync-snowflake.php >> /tmp/cfd-snowflake-sync.log 2>&1
 */

// Run from CLI only
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    die('CLI only');
}

require_once __DIR__ . '/../config/constants.php';

echo "[" . date('Y-m-d H:i:s') . "] Starting Snowflake sync...\n";

// Snowflake Python scripts location
$snowflakeDir = '/Volumes/NAS_OMD/Snowflake Connection/web_apps';

if (!is_dir($snowflakeDir)) {
    echo "ERROR: Snowflake directory not found: {$snowflakeDir}\n";
    echo "Make sure the NAS volume is mounted.\n";
    exit(1);
}

// List available scripts
$scripts = glob($snowflakeDir . '/*.py');
if (empty($scripts)) {
    echo "WARNING: No Python scripts found in {$snowflakeDir}\n";
    echo "Contents:\n";
    $contents = scandir($snowflakeDir);
    foreach ($contents as $item) {
        if ($item === '.' || $item === '..') continue;
        echo "  - {$item}\n";
    }
    echo "\nPlease configure the correct Python script path.\n";
    exit(1);
}

echo "Available scripts:\n";
foreach ($scripts as $script) {
    echo "  - " . basename($script) . "\n";
}

// Execute the sync script
// Adjust the script name below once the correct one is identified
$syncScript = $scripts[0]; // Use first available script
echo "\nRunning: python3 {$syncScript}\n";

$output = [];
$returnCode = 0;
exec("python3 " . escapeshellarg($syncScript) . " 2>&1", $output, $returnCode);

echo implode("\n", $output) . "\n";

if ($returnCode !== 0) {
    echo "\nERROR: Sync script exited with code {$returnCode}\n";
    exit($returnCode);
}

// Update sync timestamp in settings
try {
    $db = getDB();
    setSetting('snowflake_last_sync', date('Y-m-d H:i:s'));
    echo "\n[" . date('Y-m-d H:i:s') . "] Sync complete. Timestamp updated.\n";
} catch (Exception $e) {
    echo "\nWARNING: Could not update sync timestamp: " . $e->getMessage() . "\n";
}
