<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

$action = strtolower(trim((string)($_GET['action'] ?? '')));
$section = strtolower(trim((string)($_GET['section'] ?? '')));

function hub_docs_toc(): array
{
    return [
        [
            'id' => 'intro',
            'title' => 'INTRODUCTION',
            'children' => [
                ['id' => 'intro-authors', 'title' => 'Authors'],
                ['id' => 'intro-revision', 'title' => 'Revision details'],
            ],
        ],
        [
            'id' => 'deploy',
            'title' => 'LOCAL SINGLE-STEP TEST DEPLOYMENT',
            'children' => [
                ['id' => 'deploy-prep', 'title' => 'Preparations, environment'],
                ['id' => 'deploy-packages', 'title' => 'Package prerequisites by distro'],
                ['id' => 'deploy-checks', 'title' => 'Local checks'],
            ],
        ],
        ['id' => 'orchestration', 'title' => 'ORCHESTRATION MODEL', 'children' => []],
        ['id' => 'routing', 'title' => 'XHR SUPERVISED VIEW MODEL', 'children' => []],
        [
            'id' => 'ops',
            'title' => 'OPERATIONS CHECKLIST',
            'children' => [],
        ],
    ];
}

function hub_docs_section_html(string $section): string
{
    switch ($section) {
        case 'intro-authors':
            return '<p>Project owner: Anton Afanaasyeu. Implementation assistant: Cursor coding agent.</p>';
        case 'intro-revision':
            return '<p>Revision scope: landing compass interaction, XHR-driven deployment docs view, Docker orchestration model integration for next branch.</p>';
        case 'deploy-prep':
            return '<p>Prerequisites: docker + docker compose plugin, git checkout of android cast on branch <code>next</code>.</p>'
              . '<p>Run one command from repo: <code>cd orchestration && ./deploy.sh</code></p>';
        case 'deploy-packages':
            return '<table><thead><tr><th>Distro</th><th>Install steps</th></tr></thead><tbody>'
              . '<tr><td>Alpine</td><td><code>apk add docker docker-cli-compose bash git curl</code><br><code>rc-update add docker default && service docker start</code></td></tr>'
              . '<tr><td>Debian / Ubuntu</td><td><code>apt update && apt install -y docker.io docker-compose-plugin git curl</code><br><code>systemctl enable --now docker</code></td></tr>'
              . '<tr><td>Fedora</td><td><code>dnf install -y docker docker-compose-plugin git curl</code><br><code>systemctl enable --now docker</code></td></tr>'
              . '<tr><td>Arch</td><td><code>pacman -S --noconfirm docker docker-compose git curl</code><br><code>systemctl enable --now docker</code></td></tr>'
              . '</tbody></table>';
        case 'deploy-checks':
            return '<ul>'
              . '<li><code>http://localhost:8080/app/androidcast_project/</code> (hub)</li>'
              . '<li><code>http://localhost:8080/app/androidcast_project/crashes/</code> (crashes/tasks)</li>'
              . '<li><code>http://localhost:8080/app/androidcast_project/git/</code> (redirect to gitea FE)</li>'
              . '</ul>';
        case 'orchestration':
            return '<p>All infra runs in docker with shared source bind-mount where possible.</p>'
              . '<ul>'
              . '<li>landing FE (nginx): serves hub and routes subpaths</li>'
              . '<li>gitea FE (nginx) + gitea app</li>'
              . '<li>crashes FE (nginx) + php-fpm + mariadb</li>'
              . '<li>single command create/update: <code>orchestration/deploy.sh</code></li>'
              . '</ul>'
              . '<p>Base images: nginx, php-fpm, mariadb. This stays minimal and reproducible on laptop devices.</p>';
        case 'routing':
            return '<p>The Compass click opens a modal. Content is requested via XMLHttpRequest/fetch from BE endpoint '
              . '<code>/app/androidcast_project/crashes/api/hub_deploy_docs.php</code>.</p>'
              . '<p>Internal links in this modal use tree-list captions and are intercepted on frontend, then re-requested through BE. '
              . 'Browser URL bar is not changed.</p>'
              . '<p>Static assets remain at original paths and are not rewritten in this view.</p>';
        case 'ops':
            return '<ol>'
              . '<li>Pull latest <code>next</code></li>'
              . '<li>Run <code>orchestration/deploy.sh</code></li>'
              . '<li>Verify hub/crashes/gitea endpoints</li>'
              . '<li>For app changes: edit source in repo, rerun deploy script</li>'
              . '</ol>';
        case 'intro':
            return '<p>Select a topic in the table of contents to load section content from backend.</p>';
        default:
            return '<p class="muted">Section not found.</p>';
    }
}

function hub_docs_section_title(string $section): string
{
    foreach (hub_docs_toc() as $node) {
        if ($node['id'] === $section) {
            return (string)$node['title'];
        }
        foreach ($node['children'] as $child) {
            if ($child['id'] === $section) {
                return (string)$child['title'];
            }
        }
    }
    return 'Section';
}

function hub_docs_all_section_ids(): array
{
    $ids = [];
    foreach (hub_docs_toc() as $node) {
        if (!empty($node['children'])) {
            foreach ($node['children'] as $child) {
                $ids[] = (string)$child['id'];
            }
        } else {
            $ids[] = (string)$node['id'];
        }
    }
    return $ids;
}

if ($action === 'toc') {
    echo safe_json_encode([
        'ok' => true,
        'sections' => hub_docs_toc(),
        'default_section' => 'intro-authors',
        'preload' => hub_docs_all_section_ids(),
    ]);
    exit;
}

if ($section === '') {
    $section = 'intro-authors';
}

$known = hub_docs_all_section_ids();
if (!in_array($section, $known, true)) {
    $section = 'intro-authors';
}

echo safe_json_encode([
    'ok' => true,
    'section' => $section,
    'title' => hub_docs_section_title($section),
    'html' => hub_docs_section_html($section),
]);
