<?php
/**
 * CLI utility to re-run the Jupyter workspace sync for any existing user directories.
 *
 * Usage:
 *   php scripts/trigger_workspace_sync.php            # scans existing workspace folders
 *   php scripts/trigger_workspace_sync.php 12 18 42   # optional explicit person IDs
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../classes/DataSource.php';

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "This script must be executed from the command line.\n");
    exit(1);
}

$workspaceRoot = realpath(__DIR__ . '/../uploads/jupyter_workspace');
if ($workspaceRoot === false) {
    fwrite(STDERR, "Workspace root not found. Expected at uploads/jupyter_workspace.\n");
    exit(1);
}

$dataSourceManager = new DataSource($pdo);

$targetPersonIds = [];

// Allow explicit person IDs to be passed via CLI arguments.
foreach (array_slice($argv, 1) as $arg) {
    if (ctype_digit($arg)) {
        $targetPersonIds[] = (int) $arg;
    }
}

// If no explicit IDs provided, infer from existing workspace directories.
if (empty($targetPersonIds)) {
    $iterator = new DirectoryIterator($workspaceRoot);
    foreach ($iterator as $entry) {
        if ($entry->isDot() || !$entry->isDir()) {
            continue;
        }
        if (preg_match('/^user_(\d+)$/', $entry->getFilename(), $matches)) {
            $targetPersonIds[] = (int) $matches[1];
        }
    }
}

$targetPersonIds = array_values(array_unique($targetPersonIds));
sort($targetPersonIds);

if (empty($targetPersonIds)) {
    fwrite(STDOUT, "No user workspace directories detected; nothing to sync.\n");
    exit(0);
}

fwrite(STDOUT, "Preparing workspaces for person IDs: " . implode(', ', $targetPersonIds) . "\n");

$exitCode = 0;

foreach ($targetPersonIds as $personId) {
    try {
        $result = $dataSourceManager->prepareJupyterWorkspace($personId, $workspaceRoot);
        $syncedCount = count($result['synced'] ?? []);
        $missingCount = count($result['missing'] ?? []);
        fwrite(
            STDOUT,
            sprintf(
                "✔ person_id=%d synced=%d missing=%d dir=%s\n",
                $personId,
                $syncedCount,
                $missingCount,
                $result['workspace_dir'] ?? 'N/A'
            )
        );
    } catch (Throwable $e) {
        fwrite(
            STDERR,
            sprintf(
                "✖ person_id=%d failed: %s\n",
                $personId,
                $e->getMessage()
            )
        );
        $exitCode = 1;
    }
}

exit($exitCode);
