"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 setup_1 = require("../walls/07-runtime/setup/setup");
describe('setup (idempotency checks)', () => {
    let tmpDir;
    let homedir;
    beforeEach(() => {
        tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cell-setup-'));
        homedir = fs.mkdtempSync(path.join(os.tmpdir(), 'cell-setup-home-'));
    });
    afterEach(() => {
        try {
            fs.rmSync(tmpDir, { recursive: true, force: true });
        }
        catch { }
        try {
            fs.rmSync(homedir, { recursive: true, force: true });
        }
        catch { }
    });
    describe('detectProject', () => {
        it('uses package.json name when present', () => {
            const pkg = { name: 'my-cool-app', version: '1.0.0' };
            fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify(pkg), 'utf8');
            const result = (0, setup_1.detectProject)(tmpDir);
            expect(result.name).toBe('my-cool-app');
            expect(result.source).toBe('package.json');
            expect(result.packageJsonPath).toBe(path.join(tmpDir, 'package.json'));
        });
        it('falls back to folder basename when no package.json', () => {
            const subdir = path.join(tmpDir, 'no-pkg-here');
            fs.mkdirSync(subdir);
            const result = (0, setup_1.detectProject)(subdir);
            expect(result.name).toBe('no-pkg-here');
            expect(result.source).toBe('folder-basename');
        });
        it('uses override when provided', () => {
            fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ name: 'real-name' }), 'utf8');
            const result = (0, setup_1.detectProject)(tmpDir, 'override-name');
            expect(result.name).toBe('override-name');
            expect(result.source).toBe('override');
        });
        it('ignores malformed package.json', () => {
            fs.writeFileSync(path.join(tmpDir, 'package.json'), '{ not valid json', 'utf8');
            const result = (0, setup_1.detectProject)(tmpDir);
            expect(result.source).toBe('folder-basename');
        });
        it('ignores package.json without a name field', () => {
            fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ version: '1.0.0' }), 'utf8');
            const result = (0, setup_1.detectProject)(tmpDir);
            expect(result.source).toBe('folder-basename');
        });
    });
    describe('checkScanState', () => {
        it('returns done=true when .cell/personal/ has files', () => {
            const personalDir = path.join(tmpDir, '.cell', 'personal');
            fs.mkdirSync(personalDir, { recursive: true });
            fs.writeFileSync(path.join(personalDir, 'profile.json'), '{}', 'utf8');
            const state = (0, setup_1.checkScanState)(tmpDir);
            expect(state.done).toBe(true);
            expect(state.reason).toContain('1 files');
            expect(state.personalDir).toBe(personalDir);
            expect(state.scannedAt).toBeTruthy();
        });
        it('returns done=true when AGENTS.md exists (even with no .cell/personal)', () => {
            fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# user content', 'utf8');
            const state = (0, setup_1.checkScanState)(tmpDir);
            expect(state.done).toBe(true);
            expect(state.reason).toContain('AGENTS.md');
        });
        it('returns done=false when neither exists', () => {
            const state = (0, setup_1.checkScanState)(tmpDir);
            expect(state.done).toBe(false);
            expect(state.reason).toContain('no ');
        });
        it('returns done=false when .cell/personal exists but is empty', () => {
            fs.mkdirSync(path.join(tmpDir, '.cell', 'personal'), { recursive: true });
            const state = (0, setup_1.checkScanState)(tmpDir);
            expect(state.done).toBe(false);
        });
    });
    describe('checkMcpState', () => {
        it('reports all IDEs as needsWrite when no config files exist', () => {
            // homedir is empty -> none of the IDE config paths exist
            const state = (0, setup_1.checkMcpState)(homedir);
            expect(state.total).toBeGreaterThan(0);
            expect(state.done).toBe(0);
            expect(state.skipped).toBe(0);
            expect(state.needsWrite.length).toBe(state.total);
            expect(state.needsWrite).toContain('Cursor');
        });
        it('reports done=N when N IDE config files have fivo-cell wired', () => {
            // Write a Cursor config with fivo-cell already wired
            const cursorDir = path.join(homedir, '.cursor');
            fs.mkdirSync(cursorDir, { recursive: true });
            fs.writeFileSync(path.join(cursorDir, 'mcp.json'), JSON.stringify({ mcpServers: { 'fivo-cell': { url: 'http://localhost:9876/mcp' } } }), 'utf8');
            const state = (0, setup_1.checkMcpState)(homedir);
            expect(state.done).toBe(1);
            expect(state.needsWrite).not.toContain('Cursor');
            // Other IDEs should still need write
            expect(state.needsWrite.length).toBe(state.total - 1);
        });
        it('counts skipped when config file has parse errors', () => {
            const cursorDir = path.join(homedir, '.cursor');
            fs.mkdirSync(cursorDir, { recursive: true });
            fs.writeFileSync(path.join(cursorDir, 'mcp.json'), '{ not valid json', 'utf8');
            const state = (0, setup_1.checkMcpState)(homedir);
            expect(state.skipped).toBe(1);
            expect(state.done).toBe(0);
        });
    });
    describe('isDaemonRunning', () => {
        it('returns false when nothing is listening on a random port', async () => {
            // Use a random high port that nothing should be on
            const result = await (0, setup_1.isDaemonRunning)(19878, 500);
            expect(result).toBe(false);
        });
        it('returns true when an HTTP server responds on the port', async () => {
            const http = require('http');
            const server = http.createServer((_req, res) => {
                res.statusCode = 200;
                res.end('OK');
            });
            await new Promise((resolve) => server.listen(19876, '127.0.0.1', resolve));
            try {
                const result = await (0, setup_1.isDaemonRunning)(19876, 1000);
                expect(result).toBe(true);
            }
            finally {
                await new Promise((resolve) => server.close(() => resolve()));
            }
        });
        it('returns false when server returns non-200', async () => {
            const http = require('http');
            const server = http.createServer((_req, res) => {
                res.statusCode = 500;
                res.end('error');
            });
            await new Promise((resolve) => server.listen(19877, '127.0.0.1', resolve));
            try {
                const result = await (0, setup_1.isDaemonRunning)(19877, 1000);
                expect(result).toBe(false);
            }
            finally {
                await new Promise((resolve) => server.close(() => resolve()));
            }
        });
    });
});
//# sourceMappingURL=setup.test.js.map