"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
async function testLocalImport() {
    const baseURL = 'http://localhost:3001/api';
    const username = process.argv[2] || 'admin';
    const password = process.argv[3];
    const sourceFolder = process.argv[4];
    const tenantId = process.argv[5];
    if (!password) {
        console.error('Usage: ts-node scripts/test-local-import.ts <username> <password> [sourceFolder] [tenantId]');
        process.exit(1);
    }
    try {
        console.log(`Logging in as ${username} to ${baseURL}...`);
        const loginRes = await axios_1.default.post(`${baseURL}/auth/login`, {
            username,
            password
        });
        const jwtToken = loginRes.data.access_token;
        console.log('Login successful.');
        console.log('Retrieving API key...');
        const apiKeyRes = await axios_1.default.get(`${baseURL}/auth/api-key`, {
            headers: { Authorization: `Bearer ${jwtToken}` }
        });
        const apiKey = apiKeyRes.data.apiKey;
        console.log('API Key retrieved:', apiKey);
        const authHeaders = { 'x-api-key': apiKey };
        if (tenantId) {
            authHeaders['x-tenant-id'] = tenantId;
            console.log(`Target tenant set to: ${tenantId}`);
        }
        let targetPath = sourceFolder;
        let isTemp = false;
        if (!targetPath) {
            isTemp = true;
            targetPath = path.join(os.tmpdir(), `aurak-test-${Date.now()}`);
            const subDir = path.join(targetPath, 'subfolder');
            fs.mkdirSync(targetPath, { recursive: true });
            fs.mkdirSync(subDir, { recursive: true });
            fs.writeFileSync(path.join(targetPath, 'root-file.md'), '# Root File\nContent in root.', 'utf8');
            fs.writeFileSync(path.join(subDir, 'sub-file.txt'), 'Content in subfolder.', 'utf8');
            console.log(`Created temporary test structure at: ${targetPath}`);
        }
        else {
            console.log(`Using provided source folder: ${targetPath}`);
            if (!fs.existsSync(targetPath)) {
                throw new Error(`The specified folder does not exist: ${targetPath}`);
            }
        }
        const modelsRes = await axios_1.default.get(`${baseURL}/models`, {
            headers: authHeaders
        });
        const embeddingModel = modelsRes.data.find((m) => m.type === 'embedding' && m.isEnabled !== false);
        if (!embeddingModel) {
            throw new Error('No enabled embedding model found');
        }
        console.log(`Using embedding model: ${embeddingModel.id}`);
        console.log('Triggering local folder import...');
        const importRes = await axios_1.default.post(`${baseURL}/upload/local-folder`, {
            sourcePath: targetPath,
            embeddingModelId: embeddingModel.id,
            useHierarchy: true
        }, {
            headers: authHeaders
        });
        console.log('Import response:', importRes.data);
        if (isTemp) {
            console.log('Waiting for background processing (10s)...');
            await new Promise(resolve => setTimeout(resolve, 10000));
            const kbRes = await axios_1.default.get(`${baseURL}/knowledge-bases`, {
                headers: authHeaders
            });
            const importedFiles = kbRes.data.filter((f) => f.originalName === 'root-file.md' || f.originalName === 'sub-file.txt');
            console.log(`Found ${importedFiles.length} imported files in KB.`);
            if (importedFiles.length === 2) {
                console.log('SUCCESS: All files imported.');
            }
            else {
                console.log('FAILURE: Not all files were imported.');
            }
        }
        else {
            console.log('Custom folder import triggered. Please check the UI or database for results.');
        }
    }
    catch (error) {
        if (error.response) {
            console.error(`Test failed with status ${error.response.status}:`, JSON.stringify(error.response.data));
        }
        else {
            console.error('Test failed:', error.message);
        }
        process.exit(1);
    }
}
testLocalImport();
//# sourceMappingURL=test-local-import.js.map