"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 globals_1 = require("@jest/globals");
const database_1 = require("../../utils/database");
const RepositoryManager_1 = require("../../repositories/RepositoryManager");
const contextWatchHandlers_1 = require("../../handlers/contextWatchHandlers");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
(0, globals_1.describe)('Context Watch Actual Implementation Tests', () => {
    let dbManager;
    let repositories;
    let tempDbPath;
    let testSessionId;
    (0, globals_1.beforeEach)(async () => {
        tempDbPath = path.join(os.tmpdir(), `test-context-watch-actual-${Date.now()}.db`);
        dbManager = new database_1.DatabaseManager({
            filename: tempDbPath,
            maxSize: 10 * 1024 * 1024,
            walMode: true,
        });
        // Note: Watcher migrations are now automatically applied by DatabaseManager
        repositories = new RepositoryManager_1.RepositoryManager(dbManager);
        // Create test session
        const session = repositories.sessions.create({
            name: 'Test Session',
            description: 'Test session for context watch',
        });
        testSessionId = session.id;
    });
    (0, globals_1.afterEach)(() => {
        dbManager.close();
        try {
            fs.unlinkSync(tempDbPath);
            fs.unlinkSync(`${tempDbPath}-wal`);
            fs.unlinkSync(`${tempDbPath}-shm`);
        }
        catch (_e) {
            // Ignore
        }
    });
    (0, globals_1.describe)('Basic Watcher Operations', () => {
        (0, globals_1.it)('should create a watcher and detect changes', async () => {
            // Create watcher
            const createResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'create',
                filters: {
                    categories: ['task'],
                },
            }, repositories, testSessionId);
            const createResponse = JSON.parse(createResult.content[0].text);
            (0, globals_1.expect)(createResponse.created).toBe(true);
            (0, globals_1.expect)(createResponse.watcherId).toMatch(/^watch_[a-f0-9]{8}$/);
            const watcherId = createResponse.watcherId;
            // Add some context items
            repositories.contexts.save(testSessionId, {
                key: 'task_001',
                value: 'First task',
                category: 'task',
            });
            repositories.contexts.save(testSessionId, {
                key: 'note_001',
                value: 'First note',
                category: 'note',
            });
            // Poll for changes
            const pollResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'poll',
                watcherId,
            }, repositories, testSessionId);
            const pollResponse = JSON.parse(pollResult.content[0].text);
            // Should only see the task item
            (0, globals_1.expect)(pollResponse.changes).toHaveLength(1);
            (0, globals_1.expect)(pollResponse.changes[0].key).toBe('task_001');
            (0, globals_1.expect)(pollResponse.changes[0].type).toBe('CREATE');
            (0, globals_1.expect)(pollResponse.changes[0].category).toBe('task');
        });
        (0, globals_1.it)('should handle watcher lifecycle', async () => {
            // Create watcher
            const createResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'create',
            }, repositories, testSessionId);
            const { watcherId } = JSON.parse(createResult.content[0].text);
            // List watchers
            const listResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'list',
            }, repositories, testSessionId);
            const listResponse = JSON.parse(listResult.content[0].text);
            (0, globals_1.expect)(listResponse.total).toBe(1);
            (0, globals_1.expect)(listResponse.watchers[0].watcherId).toBe(watcherId);
            (0, globals_1.expect)(listResponse.watchers[0].active).toBe(true);
            // Stop watcher
            const stopResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'stop',
                watcherId,
            }, repositories, testSessionId);
            const stopResponse = JSON.parse(stopResult.content[0].text);
            (0, globals_1.expect)(stopResponse.stopped).toBe(true);
            // Try to poll stopped watcher
            const pollResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'poll',
                watcherId,
            }, repositories, testSessionId);
            (0, globals_1.expect)(pollResult.content[0].text).toContain('Error: Watcher is stopped');
        });
        (0, globals_1.it)('should apply filters correctly', async () => {
            // Create watcher with key pattern filter
            const createResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'create',
                filters: {
                    keys: ['user_*', '*_config'],
                },
            }, repositories, testSessionId);
            const { watcherId } = JSON.parse(createResult.content[0].text);
            // Add various items
            repositories.contexts.save(testSessionId, { key: 'user_profile', value: 'matches' });
            repositories.contexts.save(testSessionId, { key: 'app_config', value: 'matches' });
            repositories.contexts.save(testSessionId, { key: 'system_settings', value: 'no match' });
            // Poll for changes
            const pollResult = await (0, contextWatchHandlers_1.handleContextWatch)({
                action: 'poll',
                watcherId,
            }, repositories, testSessionId);
            const response = JSON.parse(pollResult.content[0].text);
            (0, globals_1.expect)(response.changes).toHaveLength(2);
            const keys = response.changes.map((c) => c.key);
            (0, globals_1.expect)(keys).toContain('user_profile');
            (0, globals_1.expect)(keys).toContain('app_config');
            (0, globals_1.expect)(keys).not.toContain('system_settings');
        });
    });
});
