/**
 * Designer Extension — Built-in Design Tools for the spectral coding agent
 *
 * Brings the Open Design workflow (https://github.com/nexu-io/open-design)
 * into the spectral agent as native tools. The extension provides:
 *
 *   • Design system knowledge — curated palettes, typography, spacing from
 *     Apple, Stripe, Linear, Vercel, Notion, Airbnb, and more.
 *   • Design skill workflows — structured guides for web prototypes, SaaS
 *     landings, slide decks, mobile apps, dashboards, and social carousels.
 *   • Design guidelines — anti-AI-slop rules and a 5-dimension critique
 *     framework to keep output polished.
 *   • System prompt injection — when the user asks for design work, the
 *     extension injects designer identity and anti-slop rules into context.
 *
 * Architecture:
 *   The extension registers knowledge-retrieval tools. The LLM reads design
 *   systems and skill workflows, then uses its existing tools (write, bash,
 *   read) to produce design artifact files. This matches how Open Design
 *   works: the daemon composes a system prompt, the agent does the build.
 *
 * No packages to install — everything is embedded in this extension.
 */
import { Type } from "typebox";
import { getDesignGuidelines, DISCOVERY_PROTOCOL } from "./guidelines.js";
import { findSkill, formatSkillForLLM, listSkillsForLLM, } from "./skills.js";
import { findSystem, formatSystemForLLM, listSystemsForLLM, } from "./systems.js";
// ---------------------------------------------------------------------------
// Detection — should we inject design context for this prompt?
// ---------------------------------------------------------------------------
const DESIGN_TRIGGERS = [
    "design",
    "prototype",
    "mockup",
    "landing page",
    "homepage",
    "slide",
    "deck",
    "presentation",
    "dashboard",
    "mobile app",
    "app prototype",
    "ui",
    "ux",
    "brand",
    "style",
    "visual",
    "carousel",
    "poster",
    "banner",
    "color palette",
    "typography",
    "css",
    "html template",
    "saas landing",
    "pricing page",
    "portfolio",
    "redesign",
    "wireframe",
];
function promptTriggersDesign(prompt) {
    const lower = prompt.toLowerCase();
    return DESIGN_TRIGGERS.some((t) => lower.includes(t));
}
// ---------------------------------------------------------------------------
// Tool: designer_list_systems
// ---------------------------------------------------------------------------
const ListSystemsParams = Type.Object({});
// ---------------------------------------------------------------------------
// Tool: designer_get_system
// ---------------------------------------------------------------------------
const GetSystemParams = Type.Object({
    name: Type.String({
        description: "Name of the design system to retrieve. Use designer_list_systems to see available systems.",
    }),
});
// ---------------------------------------------------------------------------
// Tool: designer_list_skills
// ---------------------------------------------------------------------------
const ListSkillsParams = Type.Object({});
// ---------------------------------------------------------------------------
// Tool: designer_get_skill
// ---------------------------------------------------------------------------
const GetSkillParams = Type.Object({
    name: Type.String({
        description: "Name of the design skill to retrieve. Use designer_list_skills to see available skills.",
    }),
});
// ---------------------------------------------------------------------------
// Tool: designer_get_guidelines
// ---------------------------------------------------------------------------
const GetGuidelinesParams = Type.Object({});
// ---------------------------------------------------------------------------
// Extension entry point
// ---------------------------------------------------------------------------
export default function designerExtension(ext) {
    // ---- Inject design context on relevant prompts ---------------------------
    // Track whether we've already injected the system prompt for this session
    let guidelinesInjected = false;
    let discoveryDone = false;
    ext.on("before_agent_start", async (event, ctx) => {
        if (!promptTriggersDesign(event.prompt))
            return;
        // First design turn: inject the discovery protocol to force clarification
        if (!discoveryDone) {
            discoveryDone = true;
            return {
                systemPrompt: `${event.systemPrompt}

---

${DISCOVERY_PROTOCOL}`,
            };
        }
        // Subsequent design turns: inject design guidelines if not already present
        if (guidelinesInjected)
            return;
        if (event.systemPrompt.includes("Designer Identity"))
            return;
        guidelinesInjected = true;
        const guidelines = getDesignGuidelines();
        return {
            systemPrompt: `${event.systemPrompt}

---

${guidelines}`,
        };
    });
    // ---- Register tools ------------------------------------------------------
    ext.registerTool({
        name: "designer_list_systems",
        label: "List Design Systems",
        description: "List available design systems with color palettes, typography, and spacing tokens. " +
            "Use this to pick a visual direction before generating HTML/CSS.",
        promptSnippet: "List available design systems (Apple, Stripe, Linear, Vercel, etc.) with color, typography, and layout tokens",
        promptGuidelines: [
            "Use designer_list_systems to see available design systems, then use designer_get_system to load the full tokens for the chosen system.",
            "Always apply a design system before generating design HTML — never use generic defaults like Inter + blue buttons.",
        ],
        parameters: ListSystemsParams,
        async execute() {
            return {
                content: [{ type: "text", text: listSystemsForLLM() }],
                details: { isError: false },
            };
        },
    });
    ext.registerTool({
        name: "designer_get_system",
        label: "Get Design System",
        description: "Get the full design system tokens (CSS custom properties, typography, layout, components) for a specific system. " +
            "Map these tokens onto your :root variables before writing any component code.",
        promptSnippet: "Get full design system tokens for a specific system (e.g. 'apple', 'stripe', 'linear')",
        parameters: GetSystemParams,
        async execute(_toolCallId, params) {
            const name = params.name;
            const system = findSystem(name);
            if (!system) {
                return {
                    content: [
                        {
                            type: "text",
                            text: `Design system "${name}" not found.\n\n${listSystemsForLLM()}`,
                        },
                    ],
                    details: { isError: true },
                };
            }
            return {
                content: [{ type: "text", text: formatSystemForLLM(system) }],
                details: { isError: false },
            };
        },
    });
    ext.registerTool({
        name: "designer_list_skills",
        label: "List Design Skills",
        description: "List available design skill workflows (web prototype, SaaS landing, slide deck, mobile app, dashboard, social carousel). " +
            "Each skill provides a structured workflow for producing a specific kind of design artifact.",
        promptSnippet: "List available design skill workflows (web prototype, SaaS landing, slide deck, mobile app, dashboard)",
        promptGuidelines: [
            "Use designer_list_skills to see what kinds of design artifacts you can produce, then use designer_get_skill to load the full workflow for the chosen skill.",
            "Follow the skill workflow exactly — it encodes best practices like pre-flight reading, seed templates, section composition patterns, and self-check checklists.",
        ],
        parameters: ListSkillsParams,
        async execute() {
            return {
                content: [{ type: "text", text: listSkillsForLLM() }],
                details: { isError: false },
            };
        },
    });
    ext.registerTool({
        name: "designer_get_skill",
        label: "Get Design Skill",
        description: "Get the full workflow guide for a specific design skill. The workflow includes HTML/CSS skeletons, " +
            "component patterns, layout patterns, content rules, and quality checklists. Follow it exactly.",
        promptSnippet: "Get full design skill workflow for a specific skill type (e.g. 'web-prototype', 'slide-deck', 'mobile-app')",
        parameters: GetSkillParams,
        async execute(_toolCallId, params) {
            const name = params.name;
            const skill = findSkill(name);
            if (!skill) {
                return {
                    content: [
                        {
                            type: "text",
                            text: `Design skill "${name}" not found.\n\n${listSkillsForLLM()}`,
                        },
                    ],
                    details: { isError: true },
                };
            }
            return {
                content: [{ type: "text", text: formatSkillForLLM(skill) }],
                details: { isError: false },
            };
        },
    });
    ext.registerTool({
        name: "designer_get_guidelines",
        label: "Get Design Guidelines",
        description: "Get the core design guidelines: anti-AI-slop rules, 5-dimension self-critique framework, and designer identity. " +
            "Use this when you need a refresher on design quality standards or to self-critique your output.",
        promptSnippet: "Get anti-slop rules and design quality guidelines",
        parameters: GetGuidelinesParams,
        async execute() {
            return {
                content: [{ type: "text", text: getDesignGuidelines() }],
                details: { isError: false },
            };
        },
    });
    process.stderr.write(`[designer] Registered 5 design tools (${DESIGN_TRIGGERS.length} trigger keywords).\n`);
}
