"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CSSTokenWriter = void 0;
const promises_1 = require("fs/promises");
const logger_1 = require("../utils/logger");
const TailwindCSSTokenAdapter_1 = require("./adapters/TailwindCSSTokenAdapter");
const GatewayClient_1 = require("./GatewayClient");
const tokenWriterPrompts_1 = require("../prompts/tokenWriterPrompts");
const log = (0, logger_1.createLogger)('CSSTokenWriter');
const ANTHROPIC_MODEL = 'claude-opus-4-6';
const MAX_OUTPUT_TOKENS = 4096;
/**
 * Converts a token registry path (e.g., category=colors, path="gray.500")
 * to its corresponding CSS custom property name (e.g., "--color-gray-500")
 */
const CATEGORY_TO_PREFIX = {
    colors: 'color',
    spacing: 'spacing',
    borderRadius: 'radius',
    fontSize: 'font-size',
    fontFamily: 'font-family',
    boxShadow: 'shadow',
};
const tokenPathToCSSVariable = (category, tokenPath) => {
    const prefix = CATEGORY_TO_PREFIX[category];
    // Convert dot-separated path to dash-separated: "gray.500" → "gray-500"
    const dashPath = tokenPath.replace(/\./g, '-');
    return `--${prefix}-${dashPath}`;
};
/**
 * Service for writing token updates to Tailwind v4 CSS @theme blocks.
 * Uses LLM to generate search/replace modifications.
 */
class CSSTokenWriter {
    adapter = new TailwindCSSTokenAdapter_1.TailwindCSSTokenAdapter();
    gateway;
    constructor(gatewayUrl, proxyUrl) {
        this.gateway = new GatewayClient_1.GatewayClient(gatewayUrl, proxyUrl);
    }
    /**
     * Update a token value in the CSS @theme block
     */
    async updateToken(projectRoot, request, configPath) {
        const { category, path: tokenPath, value } = request;
        const resolvedConfigPath = this.adapter.getConfigPath(projectRoot, configPath);
        if (!resolvedConfigPath) {
            return { success: false, error: 'CSS file with @theme block not found' };
        }
        const cssVariable = tokenPathToCSSVariable(category, tokenPath);
        log.info(`Updating ${cssVariable} to "${value}" in ${resolvedConfigPath}`);
        try {
            const configContent = await (0, promises_1.readFile)(resolvedConfigPath, 'utf-8');
            const modification = await this.generateModification(resolvedConfigPath, configContent, category, tokenPath, value, cssVariable);
            if (!modification) {
                return { success: false, error: 'Failed to generate modification' };
            }
            const newContent = configContent.replace(modification.search, modification.replacement);
            if (newContent === configContent) {
                return {
                    success: false,
                    error: 'Failed to apply modification - search text not found',
                };
            }
            await (0, promises_1.writeFile)(resolvedConfigPath, newContent, 'utf-8');
            log.info(`Successfully updated ${cssVariable}`);
            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 CSS custom property */
    async generateModification(configPath, configContent, category, tokenPath, newValue, cssVariable) {
        const prompt = this.buildPrompt(configPath, configContent, category, tokenPath, newValue, cssVariable);
        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);
            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 ${cssVariable}`,
            };
        }
        catch (error) {
            log.warn('Failed to generate modification:', error);
            return null;
        }
    }
    buildPrompt(configPath, configContent, category, tokenPath, newValue, cssVariable) {
        return (0, tokenWriterPrompts_1.buildCssTokenPrompt)(configPath, configContent, category, tokenPath, newValue, cssVariable);
    }
}
exports.CSSTokenWriter = CSSTokenWriter;
//# sourceMappingURL=CSSTokenWriter.js.map