"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TailwindConfigWriter = void 0;
const promises_1 = require("fs/promises");
const logger_1 = require("../utils/logger");
const TailwindTokenAdapter_1 = require("./adapters/TailwindTokenAdapter");
const GatewayClient_1 = require("./GatewayClient");
const tokenWriterPrompts_1 = require("../prompts/tokenWriterPrompts");
const log = (0, logger_1.createLogger)('TailwindConfigWriter');
const ANTHROPIC_MODEL = 'claude-opus-4-6';
const MAX_OUTPUT_TOKENS = 4096;
/**
 * Service for writing token updates to Tailwind config files.
 * Uses LLM to generate search/replace modifications.
 */
class TailwindConfigWriter {
    adapter = new TailwindTokenAdapter_1.TailwindTokenAdapter();
    gateway;
    constructor(gatewayUrl, proxyUrl) {
        this.gateway = new GatewayClient_1.GatewayClient(gatewayUrl, proxyUrl);
    }
    /**
     * Update a token value in the Tailwind config file
     */
    async updateToken(projectRoot, request, configPath) {
        const { category, path, value } = request;
        // Find the config file
        const resolvedConfigPath = this.adapter.getConfigPath(projectRoot, configPath);
        if (!resolvedConfigPath) {
            return { success: false, error: 'Tailwind config file not found' };
        }
        log.info(`Updating token ${category}.${path} to "${value}" in ${resolvedConfigPath}`);
        try {
            // Read current config content
            const configContent = await (0, promises_1.readFile)(resolvedConfigPath, 'utf-8');
            // Generate the modification using LLM
            const modification = await this.generateModification(resolvedConfigPath, configContent, category, path, value);
            if (!modification) {
                return { success: false, error: 'Failed to generate modification' };
            }
            // Apply the modification (search and replace)
            const newContent = configContent.replace(modification.search, modification.replacement);
            if (newContent === configContent) {
                return {
                    success: false,
                    error: 'Failed to apply modification - search text not found',
                };
            }
            // Write the updated content back to the file
            await (0, promises_1.writeFile)(resolvedConfigPath, newContent, 'utf-8');
            log.info(`Successfully updated ${category}.${path}`);
            return { success: true, configPath: resolvedConfigPath };
        }
        catch (error) {
            log.warn('Failed to update token:', error);
            return {
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error',
            };
        }
    }
    /**
     * Generate a search/replace modification for updating a token
     */
    async generateModification(configPath, configContent, category, tokenPath, newValue) {
        const prompt = this.buildPrompt(configPath, configContent, category, tokenPath, newValue);
        try {
            const rawText = await this.gateway.sendMessage({
                model: ANTHROPIC_MODEL,
                maxTokens: MAX_OUTPUT_TOKENS,
                temperature: 0.3,
                prompt,
            });
            // Strip markdown code fences if present (```json ... ```)
            const cleaned = rawText
                .replace(/^```json\s*/i, '')
                .replace(/\s*```$/i, '')
                .trim();
            const result = JSON.parse(cleaned);
            // Validate result structure
            if (!result ||
                typeof result !== 'object' ||
                !('search' in result) ||
                !('replacement' in result)) {
                log.warn('Invalid LLM response structure:', result);
                return null;
            }
            return {
                filePath: configPath,
                search: result.search,
                replacement: result.replacement,
                changes: result.changes || `Updated ${category}.${tokenPath}`,
            };
        }
        catch (error) {
            log.warn('Failed to generate modification:', error);
            return null;
        }
    }
    buildPrompt(configPath, configContent, category, tokenPath, newValue) {
        return (0, tokenWriterPrompts_1.buildTailwindTokenPrompt)(configPath, configContent, category, tokenPath, newValue);
    }
}
exports.TailwindConfigWriter = TailwindConfigWriter;
//# sourceMappingURL=TailwindConfigWriter.js.map