import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import dotenv from 'dotenv';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load .env from project root (Search up to project root from framework/utils or framework/dist/utils)
const envPaths = [
    path.resolve(__dirname, '../../.env'), // framework/utils -> root
    path.resolve(__dirname, '../../../.env'), // framework/dist/utils -> root
    path.resolve(process.cwd(), '.env') // current working directory
];
for (const envPath of envPaths) {
    if (fs.existsSync(envPath)) {
        dotenv.config({ path: envPath });
        break;
    }
}
export class ConfigManager {
    static instance;
    remoteToken = null;
    constructor() { }
    static getInstance() {
        if (!this.instance) {
            this.instance = new ConfigManager();
        }
        return this.instance;
    }
    setRemoteToken(token) {
        this.remoteToken = token;
    }
    getMongoConfig() {
        const defaultPath = path.resolve(__dirname, '../config/db.json');
        let jsonConfig = {};
        if (fs.existsSync(defaultPath)) {
            jsonConfig = JSON.parse(fs.readFileSync(defaultPath, 'utf-8'));
        }
        return {
            enabled: process.env.MONGO_ENABLED === 'true' || jsonConfig.enabled || true,
            uri: process.env.MONGODB_URI || process.env.MONGO_URI || jsonConfig.uri || 'mongodb://localhost:27017',
            dbName: process.env.MONGO_DB_NAME || jsonConfig.dbName || 'scrapit',
            collection: process.env.MONGO_COLLECTION || jsonConfig.collection || 'results'
        };
    }
    getS3Config() {
        const defaultPath = path.resolve(__dirname, '../config/s3.json');
        let jsonConfig = {};
        if (fs.existsSync(defaultPath)) {
            jsonConfig = JSON.parse(fs.readFileSync(defaultPath, 'utf-8'));
        }
        return {
            region: process.env.AWS_REGION || jsonConfig.region || 'us-east-1',
            bucket: process.env.AWS_BUCKET || jsonConfig.bucket || 'your-automation-bucket',
            folder: process.env.AWS_FOLDER || jsonConfig.folder || 'downloads',
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
        };
    }
    getAdminConfig() {
        return {
            email: process.env.ADMIN_EMAIL || 'ashish@scrapit.com',
            password: process.env.ADMIN_PASSWORD || 'ScrapAdmin@123',
            organizationId: this.getDefaultOrgId(),
            organizationName: this.getDefaultOrgName()
        };
    }
    getDefaultOrgId() {
        return process.env.DEFAULT_ORG_ID || 'ORG-SCRAPITOS';
    }
    getOrganizationId() {
        const token = this.remoteToken || process.env.SCRAPIT_TOKEN;
        if (token) {
            try {
                const base64Url = token.split('.')[1];
                const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                const payload = JSON.parse(Buffer.from(base64, 'base64').toString());
                return payload.organizationId || this.getDefaultOrgId();
            }
            catch (e) {
                return this.getDefaultOrgId();
            }
        }
        return this.getDefaultOrgId();
    }
    getDefaultOrgName() {
        return process.env.DEFAULT_ORG_NAME || 'Scrapitos Enterprise';
    }
    getJwtSecret() {
        return process.env.JWT_SECRET || 'scrapit-super-secret-key';
    }
    getPort() {
        return parseInt(process.env.PORT || '4000', 10);
    }
    getRemoteConfig() {
        const token = this.remoteToken || process.env.SCRAPIT_TOKEN || '';
        return {
            apiUrl: process.env.SCRAPIT_API_URL || 'http://localhost:4000/api',
            token,
            mode: (process.env.SCRAPIT_REGISTRY_MODE || (token ? 'api' : 'db'))
        };
    }
    getLogBaseDir() {
        const logPath = process.env.LOG_PATH;
        if (logPath) {
            return path.dirname(logPath);
        }
        return path.resolve(process.cwd(), '.logs');
    }
    getResultsBaseDir() {
        const logPath = process.env.LOG_PATH;
        if (logPath) {
            // Use the same parent directory as logs for results if LOG_PATH is provided
            return path.join(path.dirname(logPath), 'results');
        }
        return path.resolve(process.cwd(), '.results');
    }
}
