<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/scheduler.php';

$id = trim($_GET['id'] ?? '');
if (!$id || str_contains($id, '..') || !preg_match('/^[a-zA-Z0-9_.\/\-]+$/', $id)) {
    echo json_encode(['ok' => false, 'error' => 'Invalid id']);
    exit;
}

$isScript = str_ends_with($id, '.sh');
$name     = basename($id, $isScript ? '.sh' : '');
$dirName  = basename(dirname($id));   // e.g. "Media", "Rsync", "Orchestrators"
$slug     = strtolower(str_replace(['_', '-'], ' ', $name));
$parts    = explode(' ', $slug);
$first    = $parts[0] ?? '';          // e.g. "radarr" from "radarr cleanup"

// Script header (bash scripts only)
$path   = SCRIPTS_DIR . '/' . $id;
$header = ($isScript && file_exists($path)) ? vv_script_header_clean($path) : '';

// Section matcher: heading contains the full slug OR first meaningful word (>3 chars)
$matcher = function(string $heading, bool $isIntro) use ($slug, $first): bool {
    if ($isIntro) return false;
    $h = strtolower(str_replace(['_', '-'], ' ', $heading));
    return str_contains($h, $slug)
        || (strlen($first) > 3 && str_contains($h, $first));
};

// Search main README/Manual + module-level files for this script's directory
$scriptsDir  = SCRIPTS_DIR;
$searchFiles = [];
foreach (['README', 'Manual'] as $docType) {
    $main = "$scriptsDir/$docType.md";
    if (file_exists($main)) $searchFiles[] = [$docType, $main];

    $mod = "$scriptsDir/$docType-$dirName.md";
    if ($dirName && $dirName !== '.' && file_exists($mod) && $mod !== $main) {
        $searchFiles[] = ["$docType — $dirName", $mod];
    }
}

$sections = [];
foreach ($searchFiles as [$label, $file]) {
    $body = vv_readme_section($file, $matcher);
    if ($body) $sections[] = ['source' => $label, 'body' => $body];
}

echo json_encode([
    'ok'       => true,
    'name'     => $name,
    'header'   => $header,
    'sections' => $sections,
]);
