"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 });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const PROJECTS_DIR = path.join(os.homedir(), '.fivo', 'cell', 'projects');
describe('ProjectDNA', () => {
    let module;
    beforeEach(async () => {
        module = await Promise.resolve().then(() => __importStar(require('../../walls/03-knowledge/dna/project-dna')));
        if (fs.existsSync(PROJECTS_DIR)) {
            for (const f of fs.readdirSync(PROJECTS_DIR))
                fs.unlinkSync(path.join(PROJECTS_DIR, f));
        }
    });
    const makePattern = (id, category, lang, fw, from, to, signals) => ({
        patternId: id, category, description: `desc:${id}`, from, to,
        conditions: [{ type: 'language', value: lang, matchScore: 0.9 }, { type: 'framework', value: fw, matchScore: 0.8 }],
        confidence: { distribution: 'beta', alpha: 5, beta: 1, mean: 0.85, ci95: [0.6, 0.96] },
        signals: { positive: Math.round(signals * 0.7), negative: Math.round(signals * 0.3), total: signals, lastSignal: Date.now() },
        attribution: { primaryCondition: lang, conditionConfidence: 0.9, sourceFiles: [], note: '' },
        scope: 'global', survivedDays: 10,
        meta: { language: lang, subcategory: 'general', complexity: 'low', risk: 'medium', source: 'manual' },
        lifecycle: { firstSeen: Date.now(), lastSeen: Date.now(), version: 1, history: [] },
        quality: { score: 50, reuseRate: 0, successRate: 0, failureRate: 0, acceptanceRate: 0, daysSinceLastSignal: 0, age: 0 },
        relationships: { related: [], conflicting: [], complementary: [], dependencies: [] },
        ranking: { score: 0, rank: 0, factors: { confidence: 0, quality: 0, usage: 0, recency: 0, acceptance: 0 } },
    });
    test('buildProjectProfile creates file and returns profile', () => {
        const patterns = [
            makePattern('p1', 'variable_declaration', 'typescript', 'react', 'var x', 'const x', 10),
            makePattern('p2', 'function_declaration', 'typescript', 'react', 'function', 'arrow', 5),
        ];
        const profile = module.buildProjectProfile('proj-1', 'My Project', patterns);
        expect(profile.projectId).toBe('proj-1');
        expect(profile.name).toBe('My Project');
        expect(profile.totalPatterns).toBe(2);
        expect(profile.totalSignals).toBe(15);
        expect(profile.primaryLanguage).toBe('typescript');
        const loaded = module.getProjectProfile('proj-1');
        expect(loaded).not.toBeNull();
        expect(loaded.totalPatterns).toBe(2);
    });
    test('getProjectProfile returns null for missing project', () => {
        expect(module.getProjectProfile('nonexistent')).toBeNull();
    });
    test('listProjectProfiles returns all project IDs', () => {
        module.buildProjectProfile('a', 'A', []);
        module.buildProjectProfile('b', 'B', []);
        const list = module.listProjectProfiles();
        expect(list).toContain('a');
        expect(list).toContain('b');
    });
    test('deleteProjectProfile removes file', () => {
        module.buildProjectProfile('del-me', 'Delete Me', []);
        expect(module.getProjectProfile('del-me')).not.toBeNull();
        expect(module.deleteProjectProfile('del-me')).toBe(true);
        expect(module.getProjectProfile('del-me')).toBeNull();
    });
    test('compareProjects returns divergence info', () => {
        const tsPatterns = [makePattern('p1', 'variable_declaration', 'typescript', 'react', 'var', 'const', 5)];
        const pyPatterns = [makePattern('p2', 'function_declaration', 'python', 'django', 'def', 'lambda', 3)];
        module.buildProjectProfile('ts-proj', 'TS', tsPatterns);
        module.buildProjectProfile('py-proj', 'PY', pyPatterns);
        const comparison = module.compareProjects('ts-proj', 'py-proj');
        expect(comparison.similarity).toBeLessThan(50);
        expect(comparison.divergences.length).toBeGreaterThan(0);
    });
    test('compareProjects returns null if missing', () => {
        const result = module.compareProjects('exists', 'missing');
        expect(result.divergences).toContain('One or both projects not found');
    });
    test('inferArchitecture detects MVC and layered patterns', () => {
        const patterns = [
            { category: 'controller', description: 'UserController handles requests', from: 'a', to: 'b' },
            { category: 'model', description: 'UserModel defines schema', from: 'c', to: 'd' },
        ];
        const arch = module.inferArchitecture(patterns);
        expect(arch.detectedPatterns.length).toBeGreaterThanOrEqual(1);
        expect(arch.suggestedLabel).toContain('MVC');
    });
    test('detectTestingStyle finds vitest/jest style', () => {
        const patterns = [
            { description: 'describe block with it()', from: 'function', to: 'test' },
        ];
        const style = module.detectTestingStyle(patterns);
        expect(style.framework).not.toBe('unknown');
    });
    test('generateConventions returns editorconfig for TS', () => {
        const profile = {
            projectId: 'test', name: 'test', primaryLanguage: 'typescript',
            languages: [{ language: 'typescript', count: 5, pct: 50 }, { language: 'javascript', count: 5, pct: 50 }],
            categories: [{ category: 'a', count: 1, pct: 100 }],
            frameworks: [], totalPatterns: 5, totalSignals: 10,
            topPatterns: [], patternSequences: [], averageConfidence: 0.5,
            createdAt: Date.now(), updatedAt: Date.now(),
        };
        const convs = module.generateConventions(profile);
        expect(convs.some((c) => c.type === 'editorconfig')).toBe(true);
    });
});
//# sourceMappingURL=project-dna.test.js.map