"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigAttribution = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class ConfigAttribution {
    configCache = new Map();
    projectRoot;
    constructor(projectRoot) {
        this.projectRoot = projectRoot;
    }
    loadConfigs() {
        const cacheKey = this.projectRoot;
        if (this.configCache.has(cacheKey)) {
            return this.configCache.get(cacheKey);
        }
        const configs = [];
        const eslintPaths = ['.eslintrc.json', '.eslintrc.js', '.eslintrc.yaml', '.eslintrc.yml', '.eslintrc.cjs', 'eslint.config.js'];
        for (const eslintFile of eslintPaths) {
            const eslintPath = path.join(this.projectRoot, eslintFile);
            if (fs.existsSync(eslintPath)) {
                configs.push(eslintFile.endsWith('.json') ? this.parseESLint(eslintPath) : { path: eslintPath, type: 'eslint', rules: { 'eslint_config': eslintFile.split('.').pop() || 'unknown' } });
                break;
            }
        }
        const tsconfigPath = path.join(this.projectRoot, 'tsconfig.json');
        if (fs.existsSync(tsconfigPath)) {
            configs.push(this.parseTSConfig(tsconfigPath));
        }
        const prettierPaths = ['.prettierrc', '.prettierrc.json', '.prettierrc.js', '.prettierrc.yaml', '.prettierrc.yml', 'prettier.config.js'];
        for (const prettierFile of prettierPaths) {
            const prettierPath = path.join(this.projectRoot, prettierFile);
            if (fs.existsSync(prettierPath)) {
                configs.push(prettierFile.endsWith('.json') || prettierFile === '.prettierrc' ? this.parsePrettier(prettierPath) : { path: prettierPath, type: 'prettier', rules: {} });
                break;
            }
        }
        const pkgPath = path.join(this.projectRoot, 'package.json');
        if (fs.existsSync(pkgPath)) {
            configs.push(this.parsePackageJson(pkgPath));
        }
        this.configCache.set(cacheKey, configs);
        return configs;
    }
    attribute(category, from, to, configs) {
        const resolvedConfigs = configs ?? (() => { try {
            return this.loadConfigs();
        }
        catch {
            return [];
        } })();
        const conditions = [];
        for (const config of resolvedConfigs) {
            const matched = this.matchConfigToPattern(category, from, to, config);
            if (matched) {
                conditions.push(matched);
            }
        }
        conditions.sort((a, b) => b.matchScore - a.matchScore);
        const primaryCondition = conditions.length > 0
            ? conditions[0]
            : { type: 'team_convention', value: 'unknown', matchScore: 0 };
        const sourceFiles = [];
        return {
            primaryCondition,
            allConditions: conditions,
            sourceFiles,
        };
    }
    getConditionTypes() {
        return ['language', 'framework', 'file_type', 'strictness', 'team_convention'];
    }
    getStrictnessLevel(configs = this.loadConfigs()) {
        for (const config of configs) {
            if (config.type === 'tsconfig') {
                if (config.rules['strict'] === 'true')
                    return 'strict';
                return 'moderate';
            }
        }
        return 'moderate';
    }
    getLanguage(configs = this.loadConfigs()) {
        for (const config of configs) {
            if (config.type === 'tsconfig')
                return 'typescript';
            if (config.type === 'package_json' && config.rules['typescript'])
                return 'typescript';
        }
        return 'javascript';
    }
    getFramework(configs = this.loadConfigs()) {
        for (const config of configs) {
            if (config.type === 'package_json') {
                if (config.rules['next'])
                    return 'next.js';
                if (config.rules['react'])
                    return 'react';
                if (config.rules['express'])
                    return 'express';
                if (config.rules['vue'])
                    return 'vue';
                if (config.rules['svelte'])
                    return 'svelte';
                if (config.rules['angular'])
                    return 'angular';
                if (config.rules['nuxt'])
                    return 'nuxt';
                if (config.rules['remix'])
                    return 'remix';
                if (config.rules['astro'])
                    return 'astro';
                if (config.rules['fastify'])
                    return 'fastify';
                if (config.rules['nestjs'])
                    return 'nestjs';
            }
        }
        return 'unknown';
    }
    clearCache() {
        this.configCache.clear();
    }
    matchConfigToPattern(category, from, to, config) {
        const patternMap = {
            variable_declaration: {
                eslint: { condition: 'prefer-const', score: 0.95 },
                tsconfig: { condition: 'strict=true', score: 0.85 },
            },
            function_style: {
                eslint: { condition: 'prefer-arrow-callback', score: 0.9 },
            },
            quote_style: {
                prettier: { condition: 'singleQuote', score: 0.95 },
                eslint: { condition: 'quotes', score: 0.9 },
            },
            equality: {
                eslint: { condition: 'eqeqeq', score: 0.95 },
            },
            export_style: {
                eslint: { condition: 'import/prefer-default-export', score: 0.9 },
            },
            module_system: {
                tsconfig: { condition: 'module=ESNext', score: 0.85 },
            },
            promise_style: {
                eslint: { condition: 'no-async-promise-executor', score: 0.7 },
            },
            type_annotation: {
                tsconfig: { condition: 'strict=true', score: 0.9 },
            },
            error_handling: {
                eslint: { condition: 'no-throw-literal', score: 0.7 },
            },
            null_safety: {
                tsconfig: { condition: 'strictNullChecks=true', score: 0.9 },
            },
        };
        const categoryMap = patternMap[category];
        if (!categoryMap)
            return null;
        const configMatch = categoryMap[config.type];
        if (!configMatch)
            return null;
        const ruleExists = Object.keys(config.rules).some((key) => key.toLowerCase().includes(configMatch.condition.toLowerCase()));
        if (ruleExists) {
            return {
                type: this.mapConfigTypeToConditionType(config.type),
                value: configMatch.condition,
                matchScore: configMatch.score,
            };
        }
        return null;
    }
    mapConfigTypeToConditionType(configType) {
        switch (configType) {
            case 'eslint':
            case 'prettier':
                return 'strictness';
            case 'tsconfig':
                return 'language';
            case 'package_json':
                return 'framework';
            default:
                return 'team_convention';
        }
    }
    parseESLint(filePath) {
        try {
            const content = fs.readFileSync(filePath, 'utf-8');
            const parsed = JSON.parse(content);
            const rules = {};
            if (parsed.rules) {
                for (const [key, value] of Object.entries(parsed.rules)) {
                    if (typeof value === 'string') {
                        rules[key] = value;
                    }
                    else if (Array.isArray(value) && value.length > 0) {
                        rules[key] = String(value[0]);
                    }
                }
            }
            return { path: filePath, type: 'eslint', rules };
        }
        catch {
            return { path: filePath, type: 'eslint', rules: {} };
        }
    }
    parseTSConfig(filePath) {
        try {
            const content = fs.readFileSync(filePath, 'utf-8');
            const parsed = JSON.parse(content);
            const rules = {};
            const options = parsed.compilerOptions || {};
            for (const [key, value] of Object.entries(options)) {
                rules[key] = String(value);
            }
            return { path: filePath, type: 'tsconfig', rules };
        }
        catch {
            return { path: filePath, type: 'tsconfig', rules: {} };
        }
    }
    parsePrettier(filePath) {
        try {
            const content = fs.readFileSync(filePath, 'utf-8');
            const parsed = JSON.parse(content);
            const rules = {};
            for (const [key, value] of Object.entries(parsed)) {
                rules[key] = String(value);
            }
            return { path: filePath, type: 'prettier', rules };
        }
        catch {
            return { path: filePath, type: 'prettier', rules: {} };
        }
    }
    parsePackageJson(filePath) {
        try {
            const content = fs.readFileSync(filePath, 'utf-8');
            const parsed = JSON.parse(content);
            const rules = {};
            const deps = { ...parsed.dependencies, ...parsed.devDependencies };
            for (const [key] of Object.entries(deps)) {
                rules[key] = 'installed';
            }
            return { path: filePath, type: 'package_json', rules };
        }
        catch {
            return { path: filePath, type: 'package_json', rules: {} };
        }
    }
}
exports.ConfigAttribution = ConfigAttribution;
//# sourceMappingURL=config-attribution.js.map