"use strict";
// ABOUTME: Extracts CSS variables from stylesheets
// ABOUTME: Parses :root blocks to resolve var() references in design tokens
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CSSVariableExtractor = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const logger_1 = require("../../utils/logger");
const log = (0, logger_1.createLogger)('CSSVariableExtractor');
/**
 * Service for extracting CSS variables from stylesheets
 * Finds and parses :root blocks to support var() reference resolution
 */
class CSSVariableExtractor {
    projectRoot;
    constructor(projectRoot) {
        this.projectRoot = projectRoot;
    }
    /**
     * Extract all CSS variables defined in :root blocks
     * @returns Map of variable names (without --) to their values
     */
    extract() {
        const cssFiles = this.findCSSFiles();
        const variables = new Map();
        for (const filePath of cssFiles) {
            try {
                const content = fs_1.default.readFileSync(filePath, 'utf8');
                const fileVariables = this.parseCSSVariables(content);
                // Merge into main map (later files override earlier ones)
                for (const [name, value] of fileVariables) {
                    variables.set(name, value);
                }
                if (fileVariables.size > 0) {
                    log.info(`Found ${fileVariables.size} CSS variables in ${path_1.default.relative(this.projectRoot, filePath)}`);
                }
            }
            catch (error) {
                log.debug(`Could not read CSS file ${filePath}:`, error);
            }
        }
        return variables;
    }
    /**
     * TODO: Offload this to an LLM call to find the right file instead of these heuristics
     * Find potential CSS files containing global variables
     * Checks common locations for global stylesheets
     */
    findCSSFiles() {
        const possiblePaths = [
            // Root level
            'globals.css',
            'index.css',
            'styles.css',
            // App directory (Next.js)
            'app/globals.css',
            'app/layout.css',
            // Src directory
            'src/globals.css',
            'src/index.css',
            'src/styles.css',
            'src/app/globals.css',
            // Styles subdirectory
            'styles/globals.css',
            'styles/index.css',
            'src/styles/globals.css',
            'src/styles/index.css',
            'app/styles/globals.css',
            // UI subdirectory (monorepo patterns)
            'src/ui/src/index.css',
            'src/ui/src/globals.css',
            'packages/ui/src/index.css',
            'packages/ui/src/globals.css',
        ];
        const found = [];
        for (const relativePath of possiblePaths) {
            const fullPath = path_1.default.join(this.projectRoot, relativePath);
            if (fs_1.default.existsSync(fullPath)) {
                found.push(fullPath);
                log.debug(`Found CSS file: ${relativePath}`);
            }
        }
        if (found.length === 0) {
            log.debug('No global CSS files found in common locations');
        }
        return found;
    }
    /**
     * Parse CSS content to extract variable definitions from :root blocks
     * Handles both single-line and multi-line :root declarations
     * Also handles @layer base { :root { ... } } patterns common in Tailwind v4
     */
    parseCSSVariables(content) {
        const variables = new Map();
        // TODO: Make this more readable
        // First, extract all variable declarations from :root blocks
        // This regex handles :root anywhere in the file, including inside @layer
        const rootBlockRegex = /:root\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/gs;
        const matches = content.matchAll(rootBlockRegex);
        for (const match of matches) {
            const blockContent = match[1];
            this.extractVariablesFromBlock(blockContent, variables);
        }
        // Also check for CSS variables in html or * selectors (less common but possible)
        const htmlBlockRegex = /html\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/gs;
        const htmlMatches = content.matchAll(htmlBlockRegex);
        for (const match of htmlMatches) {
            const blockContent = match[1];
            this.extractVariablesFromBlock(blockContent, variables);
        }
        return variables;
    }
    /**
     * Extract CSS variable declarations from a block of CSS
     */
    extractVariablesFromBlock(blockContent, variables) {
        // Extract individual variable declarations
        // Matches: --variable-name: value;
        // Value can contain spaces, numbers, percentages, etc.
        const variableRegex = /--([\w-]+)\s*:\s*([^;]+);/g;
        const varMatches = blockContent.matchAll(variableRegex);
        for (const varMatch of varMatches) {
            const name = varMatch[1].trim();
            const value = varMatch[2].trim();
            variables.set(name, value);
            log.debug(`Extracted CSS variable: --${name}: ${value}`);
        }
    }
    /**
     * Resolve a token value containing CSS variable references
     * Example: 'hsl(var(--muted))' + { muted: '210 40% 96.1%' } -> 'hsl(210 40% 96.1%)'
     */
    resolveValue(tokenValue, variables) {
        // Match var(--name) patterns
        const varRegex = /var\(--([^)]+)\)/g;
        return tokenValue.replace(varRegex, (match, varName) => {
            const resolvedValue = variables.get(varName.trim());
            if (resolvedValue) {
                log.debug(`Resolved var(--${varName}) to ${resolvedValue}`);
                return resolvedValue;
            }
            log.warn(`Could not resolve CSS variable: --${varName}`);
            return match; // Keep original if not found
        });
    }
}
exports.CSSVariableExtractor = CSSVariableExtractor;
//# sourceMappingURL=CSSVariableExtractor.js.map