"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateCommentStyleVariants = exports.readFileExcerpts = void 0;
const path_1 = __importDefault(require("path"));
const fs_1 = require("fs");
const v3_1 = require("zod/v3");
const logger_1 = require("../utils/logger");
const commentVariationPrompts_1 = require("../prompts/commentVariationPrompts");
const GatewayClient_1 = require("./GatewayClient");
const log = (0, logger_1.createLogger)('CommentVariationService');
const MIN_VARIANT_COUNT = 2;
const MAX_VARIANT_COUNT = 5;
/**
 * Sonnet 4.6 is fast enough for direction-text generation while still
 * producing coherent multi-direction designs. Phase 2 (code generation) keeps
 * using Opus through the agent loop where structural reasoning matters more.
 */
const DEFAULT_VARIATION_MODEL = 'claude-sonnet-4-6';
const DEFAULT_AGENT_CWD = process.cwd();
const MAX_TOKENS = 4000;
const TEMPERATURE = 0.7;
const MAX_FILES_FOR_CONTEXT = 3;
const MAX_BYTES_PER_FILE = 6000;
const VARIATION_SYSTEM_PROMPT = `You are a senior design systems engineer producing structured style-variation output for one selected comment target with nearby UI context.

Use the provided element, sibling, and file context to propose coherent visual directions. Nearby sibling/container adjustments are allowed when necessary for a coherent result.

Submit your final output by calling the submit_variants tool exactly once.`;
const variantSchema = v3_1.z.object({
    label: v3_1.z.string(),
    summary: v3_1.z.string(),
    changeSpec: v3_1.z.string(),
});
const responseSchema = v3_1.z.object({
    variants: v3_1.z.array(variantSchema),
});
const SUBMIT_VARIANTS_TOOL = {
    name: 'submit_variants',
    strict: true,
    description: 'Submit the final list of style variants for the commented element. Call this exactly once with all variants.',
    input_schema: {
        type: 'object',
        properties: {
            variants: {
                type: 'array',
                items: {
                    type: 'object',
                    properties: {
                        label: { type: 'string' },
                        summary: { type: 'string' },
                        changeSpec: { type: 'string' },
                    },
                    required: ['label', 'summary', 'changeSpec'],
                    additionalProperties: false,
                },
            },
        },
        required: ['variants'],
        additionalProperties: false,
    },
};
const readFileExcerpts = async (projectPath, element) => {
    const filePaths = element.filePaths?.map((f) => f.filePath).slice(0, MAX_FILES_FOR_CONTEXT) ??
        [];
    const excerpts = [];
    for (const relPath of filePaths) {
        const absPath = path_1.default.isAbsolute(relPath)
            ? relPath
            : path_1.default.join(projectPath, relPath);
        try {
            const stat = await fs_1.promises.stat(absPath);
            if (!stat.isFile())
                continue;
            const buf = await fs_1.promises.readFile(absPath, 'utf8');
            const content = buf.length > MAX_BYTES_PER_FILE
                ? buf.slice(0, MAX_BYTES_PER_FILE) + '\n... (truncated)'
                : buf;
            excerpts.push({ path: relPath, content });
        }
        catch (e) {
            log.debug(`Skipping file excerpt for ${relPath}:`, e);
        }
    }
    return excerpts;
};
exports.readFileExcerpts = readFileExcerpts;
/**
 * Generates style-variant directions for a commented element by calling the
 * gateway directly with a forced tool-use schema. Skips the agent loop because
 * direction text doesn't require codebase exploration — the relevant file
 * contents are pre-loaded into the prompt.
 */
const generateCommentStyleVariants = async ({ instruction, element, variantCount, projectPath, model, }) => {
    if (variantCount < MIN_VARIANT_COUNT ||
        variantCount > MAX_VARIANT_COUNT ||
        !Number.isInteger(variantCount)) {
        throw new Error('variantCount must be an integer between 2 and 5');
    }
    const cwd = projectPath || DEFAULT_AGENT_CWD;
    const fileExcerpts = await (0, exports.readFileExcerpts)(cwd, element);
    const prompt = (0, commentVariationPrompts_1.buildCommentVariationPrompt)(instruction, element, variantCount, fileExcerpts);
    log.info(`Comment variation request — model=${model ?? DEFAULT_VARIATION_MODEL} files=${fileExcerpts.length} count=${variantCount}`);
    const gateway = new GatewayClient_1.GatewayClient();
    const startedAt = Date.now();
    const toolInput = await gateway.sendToolUse({
        model: model ?? DEFAULT_VARIATION_MODEL,
        maxTokens: MAX_TOKENS,
        temperature: TEMPERATURE,
        system: VARIATION_SYSTEM_PROMPT,
        prompt,
        tool: SUBMIT_VARIANTS_TOOL,
        cacheSystemPrompt: true,
    });
    log.info(`Comment variation completed in ${Date.now() - startedAt}ms`);
    const parsed = responseSchema.safeParse(toolInput);
    if (!parsed.success) {
        log.warn('Variation tool input failed schema validation', {
            validationError: parsed.error.flatten(),
            received: toolInput,
        });
        throw new Error('Invalid variation response from model');
    }
    if (parsed.data.variants.length !== variantCount) {
        log.warn('Variation count mismatch', {
            expected: variantCount,
            received: parsed.data.variants.length,
        });
        throw new Error('Invalid variation response from model');
    }
    return parsed.data.variants;
};
exports.generateCommentStyleVariants = generateCommentStyleVariants;
//# sourceMappingURL=CommentVariationService.js.map