<?php
/**
 * Domain operating guide for Bricks design-system and composition work.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Support;

/**
 * Definitive SOP and architect guidance for chat and MCP.
 */
final class OperatingGuide
{
    /**
     * @return array<string, mixed>
     */
    public static function build(?string $topic = null): array
    {
        $topics = self::topics();
        $topic  = $topic !== null && $topic !== '' ? sanitize_key($topic) : null;

        if ($topic !== null && !isset($topics[$topic])) {
            return [
                'error'            => 'unknown_topic',
                'topic'            => $topic,
                'available_topics' => array_keys($topics),
            ];
        }

        $selected = $topic === null ? $topics : [$topic => $topics[$topic]];

        return [
            'sop'                => self::sop(),
            'design_convention'  => DesignConventionStore::get(),
            'detected_framework' => (new ExternalFrameworkDetector())->detect(),
            'skill_reference'    => 'lolacore-bricks-system-architect',
            'playbook_reference' => 'bricks-anatomy',
            'playbooks'          => ['bricks-anatomy', 'arranque-de-proyecto'],
            'topics'             => $selected,
        ];
    }

    public static function sop(): string
    {
        $parts = [
            'SOP: Call getBricksOverview before proposing class, variable, theme style, page, template, or component changes.',
            'Read design_convention and write inside that vocabulary. Prefer existing classes and variables over raw values.',
            'If index.coverage.complete is false, call rebuildDesignIndex until finished is true. Always return coverage on index-backed answers.',
            'getPageStructure before composing. describeElementControls before unfamiliar elements. Shortcuts (addSection, addHeading, addText, addImage, addButton) for conversational builds.',
            'Preview template conditions and component instance impact before those writes. Clone and bulk writes name every target page and resume from offset if a page fails.',
            'Never write executeCode, code signatures, custom JS interactions, or external image URLs.',
            'Pull ACF or WooCommerce sibling abilities when the question needs fields or store context. Shop abilities exist only when WooCommerce is active.',
            'Every write goes through confirm-before-write with structured previews (impact, batch, coverage, vocabulary_notes).',
            'MCP sessions must call getBricksOperatingGuide to match chat architect criteria.',
        ];

        $convention = DesignConventionStore::get();
        if (trim((string) ($convention['naming_pattern'] ?? '')) !== '') {
            $parts[] = 'Saved naming pattern: ' . (string) $convention['naming_pattern'] . '.';
        }

        if (trim((string) ($convention['variable_policy'] ?? '')) !== '') {
            $parts[] = 'Variable policy: ' . (string) $convention['variable_policy'] . '.';
        }

        return implode(' ', $parts);
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    private static function topics(): array
    {
        return [
            'naming' => [
                'title'   => 'Naming global tokens',
                'summary' => 'Use semantic names tied to role, not appearance (btn-primary, not blue-button).',
                'rules'   => [
                    'Classes: role + variant (card, card-featured).',
                    'Variables: category prefix when helpful (color-brand, space-section).',
                    'Components: noun describing the reusable block (hero-pricing, testimonial-card).',
                    'When vocabulary_notes propose a name, offer it — do not block the write.',
                ],
            ],
            'variables_vs_values' => [
                'title'   => 'Variable vs raw value',
                'summary' => 'Prefer variables for anything reused across classes, theme styles, or components.',
                'rules'   => [
                    'Colors, spacing, and typography scales belong in global variables or the color palette.',
                    'Base site typography belongs in a theme style, not duplicated as variables.',
                    'One-off tweaks on a single element can stay as raw values.',
                    'If a value appears twice, promote it to a variable before the next edit.',
                    'Import brand palettes with one batch setGlobalVariable call.',
                ],
            ],
            'merge_criteria' => [
                'title'   => 'When to merge classes',
                'summary' => 'Merge only when settings are identical and the name difference is historical noise.',
                'rules'   => [
                    'Run getClassUsage on both classes before merging.',
                    'Respect protected_prefixes from the saved design convention.',
                    'Never merge locked classes without explicit confirmation.',
                ],
            ],
            'composition' => [
                'title'   => 'Compose and restyle pages',
                'summary' => 'Read the tree, use site classes, prefer shortcuts for conversational builds.',
                'rules'   => [
                    'getPageStructure before insert, move, duplicate, or delete.',
                    'addSection/addHeading/addText/addImage/addButton apply site classes in one confirmation.',
                    'insertElement after describeElementControls for unfamiliar types.',
                    'Images from the media library only. External URLs are rejected.',
                    'styleElement and applyClasses for breakpoints and states.',
                    'listDynamicDataTags before setDynamicContent. Custom JS interactions are refused.',
                ],
            ],
            'templates_components' => [
                'title'   => 'Templates and components',
                'summary' => 'Preview template scope and component instance impact before writing.',
                'rules'   => [
                    'createTemplate + setTemplateContent for headers, footers, and layouts.',
                    'updateTemplateConditions shows which pages a condition would cover.',
                    'duplicateTemplate remaps element IDs. deleteTemplate moves to trash.',
                    'createComponentFromElement from a branch. updateComponent returns impact.instances.',
                    'Nesting stops at 10. Detach replaces one instance with regular elements.',
                ],
            ],
            'batch' => [
                'title'   => 'Clone and bulk writes',
                'summary' => 'Name every target page in the preview. Resume from offset if a page fails.',
                'rules'   => [
                    'cloneStructure copies a branch with new IDs and per-destination copy.',
                    'bulkUpdateContent and bulkApplyClasses match by class, name, or position.',
                    'batch_size default 5, max 20. Failure at page N keeps earlier pages.',
                    'Class selectors on an incomplete index add coverage_note.',
                ],
            ],
            'shop' => [
                'title'   => 'WooCommerce shop surface',
                'summary' => 'Shop abilities register only when WooCommerce is active.',
                'rules'   => [
                    'getWooBricksSurface first to see present and missing shop templates.',
                    'createWooTemplate for product, archive, cart, checkout, or account.',
                    'addProductElement for title, price, gallery, add-to-cart, and related elements.',
                    'getProductElementsCatalog lists 47 insertable Woo elements.',
                ],
            ],
            'project_bootstrap' => [
                'title'   => 'Project bootstrap order',
                'summary' => 'Read before write; convention before tokens; chrome before pages; clone instead of repeating.',
                'steps'   => [
                    'getBricksOverview',
                    'getBricksOperatingGuide',
                    'rebuildDesignIndex until coverage.complete is true',
                    'setDesignConvention when no convention is saved',
                    'getGlobalVariables + getGlobalClasses',
                    'setGlobalVariable (batch) + updateThemeStyle for typography',
                    'createTemplate + setTemplateContent for header and footer',
                    'updateTemplateConditions with scope preview',
                    'addSection / content shortcuts on the first pages using site classes',
                    'cloneStructure when the same layout repeats across pages',
                    'getWooBricksSurface when WooCommerce is active and shop templates are needed',
                    'describeElementControls before editing unfamiliar elements',
                ],
            ],
        ];
    }
}
