<?php
// Combine all SQL fragments into __install/easystream.sql
// Usage: php f_scripts/combine_sql.php

declare(strict_types=1);

$root = realpath(__DIR__ . '/..');
$installDir = $root . DIRECTORY_SEPARATOR . '__install';
$deployDir  = $root . DIRECTORY_SEPARATOR . 'deploy';
$baseFile   = $installDir . DIRECTORY_SEPARATOR . 'easystream.sql';
$backupFile = $installDir . DIRECTORY_SEPARATOR . 'easystream.sql.backup';

if (!file_exists($baseFile)) {
    fwrite(STDERR, "Base SQL not found: {$baseFile}\n");
    exit(1);
}

$fragments = [
    $installDir . DIRECTORY_SEPARATOR . 'install_settings_system.sql',
    $installDir . DIRECTORY_SEPARATOR . 'updatedb_site.sql',
    $installDir . DIRECTORY_SEPARATOR . 'updatedb_chat.sql',
    $deployDir  . DIRECTORY_SEPARATOR . 'create_social_tables.sql',
];

// Read base
$base = file_get_contents($baseFile);
if ($base === false) {
    fwrite(STDERR, "Failed to read base SQL file.\n");
    exit(1);
}

// Backup current base
@copy($baseFile, $backupFile);

$combined = rtrim($base) . "\n\n-- =====================================================================\n-- Combined migrations appended by f_scripts/combine_sql.php\n-- Timestamp: " . date('c') . "\n-- =====================================================================\n\n";

foreach ($fragments as $frag) {
    if (!file_exists($frag)) { continue; }
    $sz = filesize($frag);
    if ($sz === false || $sz === 0) { continue; }
    $content = file_get_contents($frag);
    if ($content === false) { continue; }
    $combined .= "\n\n-- >>> BEGIN: " . basename($frag) . "\n\n" . trim($content) . "\n\n-- <<< END: " . basename($frag) . "\n";
}

// Write back
if (file_put_contents($baseFile, $combined) === false) {
    fwrite(STDERR, "Failed to write combined SQL file.\n");
    exit(1);
}

echo "Combined SQL written to: {$baseFile}\nBackup saved to: {$backupFile}\n";
exit(0);

