import * as plugins from '../plugins.js';
import type * as interfaces from '../interfaces/index.js';

/**
 * Configuration manager for tsview.
 * Reads configuration from .nogit/env.json (gitzone service format)
 * or accepts programmatic configuration.
 */
export class TsViewConfig {
  private storageConfig: interfaces.IStorageConfig | null = null;
  private mongoConfig: interfaces.IMongoConfig | null = null;

  /**
   * Load configuration from .nogit/env.json
   * @param cwd - Working directory (defaults to process.cwd())
   */
  public async loadFromEnv(cwd: string = process.cwd()): Promise<void> {
    const envPath = plugins.path.join(cwd, '.nogit', 'env.json');

    try {
      const factory = plugins.smartfile.SmartFileFactory.nodeFs();
      const envFile = await factory.fromFilePath(envPath);
      var envContent = envFile.parseContentAsString();
    } catch (err) {
      console.log(`No .nogit/env.json found at ${envPath}`);
      return;
    }
    const envConfig: interfaces.IEnvConfig = JSON.parse(envContent);

    // Parse S3 config
    if (envConfig.S3_HOST || envConfig.S3_ENDPOINT) {
      this.storageConfig = {
        endpoint: envConfig.S3_ENDPOINT || envConfig.S3_HOST || '',
        port: envConfig.S3_PORT ? parseInt(envConfig.S3_PORT, 10) : undefined,
        accessKey: envConfig.S3_ACCESSKEY || '',
        accessSecret: envConfig.S3_SECRETKEY || '',
        useSsl: envConfig.S3_USESSL === true || envConfig.S3_USESSL === 'true',
      };
    }

    // Parse MongoDB config
    if (envConfig.MONGODB_URL) {
      this.mongoConfig = {
        mongoDbUrl: envConfig.MONGODB_URL,
        mongoDbName: envConfig.MONGODB_NAME || 'test',
      };
    } else if (envConfig.MONGODB_HOST) {
      // Build URL from parts
      const host = envConfig.MONGODB_HOST;
      const port = envConfig.MONGODB_PORT || '27017';
      const user = envConfig.MONGODB_USER;
      const pass = envConfig.MONGODB_PASS;
      const dbName = envConfig.MONGODB_NAME || 'test';

      let url: string;
      if (user && pass) {
        url = `mongodb://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${host}:${port}`;
      } else {
        url = `mongodb://${host}:${port}`;
      }

      this.mongoConfig = {
        mongoDbUrl: url,
        mongoDbName: dbName,
      };
    }
  }

  /**
   * Set S3 configuration programmatically
   */
  public setStorageConfig(config: interfaces.IStorageConfig): void {
    this.storageConfig = config;
  }

  /**
   * Set MongoDB configuration programmatically
   */
  public setMongoConfig(config: interfaces.IMongoConfig): void {
    this.mongoConfig = config;
  }

  /**
   * Get S3 configuration
   */
  public getStorageConfig(): interfaces.IStorageConfig | null {
    return this.storageConfig;
  }

  /**
   * Get MongoDB configuration
   */
  public getMongoConfig(): interfaces.IMongoConfig | null {
    return this.mongoConfig;
  }

  /**
   * Check if S3 is configured
   */
  public hasStorage(): boolean {
    return this.storageConfig !== null && !!this.storageConfig.endpoint && !!this.storageConfig.accessKey;
  }

  /**
   * Check if MongoDB is configured
   */
  public hasMongo(): boolean {
    return this.mongoConfig !== null && !!this.mongoConfig.mongoDbUrl;
  }
}
