"use strict";
/**
 * DocsSubAgent Implementation
 *
 * Specialized sub-agent for generating documentation.
 * Uses Claude Haiku for efficient documentation generation.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.DocsSubAgent = void 0;
const subAgentPersonalities_1 = require("../../constants/subAgentPersonalities");
const hybridAIClient_1 = require("../../utils/hybridAIClient");
class DocsSubAgent {
    constructor() {
        this.name = "DocsSubAgent";
        this.description = "Technical writer specializing in clear, comprehensive documentation";
        const personality = (0, subAgentPersonalities_1.getSubAgentPersonality)(this.name);
        if (!personality) {
            throw new Error(`Personality not found for ${this.name}`);
        }
        this.personality = personality.systemPrompt;
        this.llmProvider = personality.llmProvider;
        this.expertise = personality.expertise;
        this.ai = new hybridAIClient_1.HybridAIClient();
    }
    async run(input) {
        const { code, component, format } = input;
        try {
            // Generate documentation using AI
            const prompt = this.buildDocumentationPrompt(code, component, format);
            const { text: aiResponse } = await this.ai.generateText(prompt);
            const content = aiResponse || this.generateBasicDocumentation(component, format);
            const estimatedReadTime = this.calculateReadTime(content, format);
            return {
                content,
                format,
                estimatedReadTime,
            };
        }
        catch (error) {
            throw new Error(`Documentation generation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
    }
    async validate(input) {
        return !!(input.code && input.component && input.format);
    }
    async getStatus() {
        return {
            name: this.name,
            status: "idle",
            errorCount: 0,
            successCount: 0,
        };
    }
    generateComponentName(description) {
        // Convert description to PascalCase component name
        return description
            .split(" ")
            .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
            .join("")
            .replace(/[^a-zA-Z0-9]/g, "");
    }
    generateReadme(component) {
        // Handle both string and object inputs
        let name, description, type, userStories, actionFunctions, dependencies, tags;
        if (typeof component === "string") {
            // Simple string input - create basic documentation structure
            name = this.generateComponentName(component);
            description = component;
            type = "form";
            userStories = [
                `As a user, I want to use ${name} to ${component.toLowerCase()}`,
            ];
            actionFunctions = ["handleSubmit", "handleChange"];
            dependencies = ["react", "tailwindcss"];
            tags = ["ui", "component"];
        }
        else {
            // Structured component object
            ({
                name,
                description,
                type,
                userStories,
                actionFunctions,
                dependencies,
                tags,
            } = component);
        }
        return `# ${name} Component

## Overview

${description}

## Component Type

**${type}** - ${this.getTypeDescription(type)}

## User Stories

${userStories
            .map((story, index) => `${index + 1}. ${story}`)
            .join("\n")}

## Action Functions

${actionFunctions.map((func) => `- \`${func}\``).join("\n")}

## Dependencies

${dependencies.map((dep) => `- \`${dep}\``).join("\n")}

## Tags

${tags.map((tag) => `\`${tag}\``).join(" ")}

## Usage

\`\`\`tsx
import { ${name} } from '@/components/${name}';

function MyPage() {
  return (
    <${name} />
  );
}
\`\`\`

## Props

${this.generatePropsDocumentation(type)}

## Examples

${this.generateExamples(type, name)}

## Best Practices

${this.generateBestPractices(type)}

## Accessibility

${this.generateAccessibilityNotes(type)}

---
*Generated by MyContext DocsSubAgent*
`;
    }
    generateInlineComments(code, component) {
        const { name, description, userStories, actionFunctions } = component;
        return `/**
 * ${name} Component
 * 
 * ${description}
 * 
 * User Stories:
${userStories.map((story) => ` * - ${story}`).join("\n")}
 * 
 * Action Functions:
${actionFunctions.map((func) => ` * - ${func}`).join("\n")}
 * 
 * @component
 * @example
 * <${name} />
 */
`;
    }
    generateInlineDocs(code, component) {
        // Add JSDoc comments to the existing code
        const { name, description, userStories, actionFunctions } = component;
        const headerComment = `/**
 * ${name} Component
 * 
 * ${description}
 * 
 * User Stories:
${userStories.map((story) => ` * - ${story}`).join("\n")}
 * 
 * Action Functions:
${actionFunctions.map((func) => ` * - ${func}`).join("\n")}
 */\n\n`;
        return headerComment + code;
    }
    getTypeDescription(type) {
        const descriptions = {
            form: "Interactive form component for data input and submission",
            layout: "Structural component for organizing page layout",
            card: "Container component for displaying content in a card format",
            button: "Interactive button component for user actions",
            input: "Form input component for data entry",
            modal: "Overlay component for focused interactions",
            table: "Data display component for tabular information",
            navigation: "Navigation component for site structure",
            list: "List component for displaying collections of items",
            chart: "Data visualization component for charts and graphs",
        };
        return descriptions[type] || "Custom component for specific functionality";
    }
    generatePropsDocumentation(type) {
        const propsMap = {
            form: `
- \`onSubmit?: (data: any) => void\` - Callback function when form is submitted
- \`loading?: boolean\` - Loading state for form submission
- \`error?: string\` - Error message to display
- \`className?: string\` - Additional CSS classes`,
            layout: `
- \`children: React.ReactNode\` - Content to be rendered inside the layout
- \`sidebar?: React.ReactNode\` - Optional sidebar content
- \`className?: string\` - Additional CSS classes`,
            card: `
- \`title?: string\` - Card title
- \`content?: React.ReactNode\` - Card content
- \`actions?: React.ReactNode\` - Action buttons or links
- \`className?: string\` - Additional CSS classes`,
            button: `
- \`variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"\` - Button style variant
- \`size?: "default" | "sm" | "lg" | "icon"\` - Button size
- \`onClick?: () => void\` - Click handler
- \`disabled?: boolean\` - Disabled state
- \`className?: string\` - Additional CSS classes`,
        };
        return (propsMap[type] ||
            `
- \`className?: string\` - Additional CSS classes
- \`...props\` - Additional HTML attributes`);
    }
    generateExamples(type, name) {
        const examples = {
            form: `
### Basic Form
\`\`\`tsx
<${name} onSubmit={(data) => console.log(data)} />
\`\`\`

### Form with Loading State
\`\`\`tsx
<${name} 
  onSubmit={handleSubmit} 
  loading={isLoading} 
  error={errorMessage} 
/>
\`\`\``,
            card: `
### Basic Card
\`\`\`tsx
<${name} title="Card Title" content="Card content here" />
\`\`\`

### Card with Actions
\`\`\`tsx
<${name} 
  title="User Profile" 
  content={<UserProfileContent />}
  actions={<Button>Edit Profile</Button>}
/>
\`\`\``,
            button: `
### Primary Button
\`\`\`tsx
<${name} variant="default" onClick={handleClick}>
  Click Me
</${name}>
\`\`\`

### Destructive Button
\`\`\`tsx
<${name} variant="destructive" onClick={handleDelete}>
  Delete
</${name}>
\`\`\``,
        };
        return (examples[type] ||
            `
### Basic Usage
\`\`\`tsx
<${name} />
\`\`\`

### With Custom Styling
\`\`\`tsx
<${name} className="custom-styles" />
\`\`\``);
    }
    generateBestPractices(type) {
        const practices = {
            form: `
- Always provide clear error messages
- Use appropriate input types for better UX
- Implement proper form validation
- Consider accessibility with proper labels
- Handle loading states gracefully`,
            card: `
- Keep card content focused and relevant
- Use consistent spacing and typography
- Ensure proper contrast for readability
- Consider responsive behavior
- Use semantic HTML structure`,
            button: `
- Use appropriate button variants for different actions
- Provide clear, action-oriented text
- Consider button size for touch targets
- Implement proper disabled states
- Use semantic button types`,
        };
        return (practices[type] ||
            `
- Follow React best practices
- Use semantic HTML elements
- Ensure proper accessibility
- Test across different browsers
- Consider performance implications`);
    }
    generateAccessibilityNotes(type) {
        const accessibility = {
            form: `
- Use proper form labels and fieldset elements
- Implement ARIA attributes for form validation
- Ensure keyboard navigation works properly
- Provide clear error announcements
- Use appropriate input types for screen readers`,
            card: `
- Use semantic HTML structure
- Ensure proper heading hierarchy
- Provide alternative text for images
- Maintain sufficient color contrast
- Support keyboard navigation`,
            button: `
- Use semantic button elements
- Provide clear, descriptive text
- Implement proper focus indicators
- Support keyboard activation
- Use appropriate ARIA attributes`,
        };
        return (accessibility[type] ||
            `
- Follow WCAG 2.1 guidelines
- Ensure keyboard navigation support
- Maintain proper color contrast
- Use semantic HTML elements
- Test with screen readers`);
    }
    /**
     * Build documentation prompt for Ollama
     */
    buildDocumentationPrompt(code, component, format) {
        const componentInfo = typeof component === "string" ? component : JSON.stringify(component);
        const formatInstructions = {
            readme: "Generate a comprehensive README documentation for this component",
            comments: "Generate JSDoc comments for this component code",
            inline: "Add JSDoc comments to the existing component code",
        };
        return `[mycontext] Plan: plan → generate → QA → docs → preview (→ checks)\nYou are a technical documentation expert. ${formatInstructions[format] ||
            formatInstructions.readme}.

Component Information:
${componentInfo}

${code
            ? `Component Code:
\`\`\`tsx
${code}
\`\`\``
            : ""}

Requirements:
- Use clear, professional technical writing
- Include usage examples
- Add proper JSDoc comments if generating inline documentation
- Follow React/TypeScript documentation best practices
- Be concise but comprehensive

Generate the documentation:`;
    }
    /**
     * Calculate estimated read time based on content length
     */
    calculateReadTime(content, format) {
        const wordsPerMinute = 200; // Average reading speed
        const wordCount = content.split(/\s+/).length;
        const baseTime = Math.ceil(wordCount / wordsPerMinute);
        // Adjust based on format complexity
        switch (format) {
            case "readme":
                return Math.max(baseTime, 3); // Minimum 3 minutes for README
            case "comments":
                return Math.max(baseTime, 1); // Minimum 1 minute for comments
            case "inline":
                return Math.max(baseTime, 2); // Minimum 2 minutes for inline docs
            default:
                return Math.max(baseTime, 2);
        }
    }
    generateBasicDocumentation(component, format) {
        const componentName = typeof component === "string" ? component : component.name || "Component";
        switch (format) {
            case "readme":
                return this.generateReadme(component);
            case "inline":
                return `// ${componentName} - Basic component documentation
// This is a fallback documentation template
// Configure an AI provider for full documentation generation`;
            case "storybook":
                return `// Storybook story for ${componentName}
// This is a fallback template
// Configure an AI provider for full Storybook generation`;
            default:
                return `# ${componentName} Documentation\n\nThis is a fallback documentation template.`;
        }
    }
}
exports.DocsSubAgent = DocsSubAgent;
//# sourceMappingURL=DocsSubAgent.js.map