import * as plugins from '../plugins.ts';
import { logger } from '../logging.ts';
import { ConnectionManager } from './connectionmanager.ts';
import { OpsServer } from '../opsserver/index.ts';
import { StorageManager } from '../storage/index.ts';
import { CacheDb, CacheCleaner, CachedProject } from '../cache/index.ts';
import { resolvePaths } from '../paths.ts';

/**
 * Main GitOps application orchestrator
 */
export class GitopsApp {
  public storageManager: StorageManager;
  public smartSecret: plugins.smartsecret.SmartSecret;
  public connectionManager: ConnectionManager;
  public opsServer: OpsServer;
  public cacheDb: CacheDb;
  public cacheCleaner: CacheCleaner;

  constructor() {
    const paths = resolvePaths();
    this.storageManager = new StorageManager({
      backend: 'filesystem',
      fsPath: paths.defaultStoragePath,
    });
    this.smartSecret = new plugins.smartsecret.SmartSecret({ service: 'gitops' });
    this.connectionManager = new ConnectionManager(this.storageManager, this.smartSecret);

    this.cacheDb = CacheDb.getInstance({
      storagePath: paths.defaultTsmDbPath,
      dbName: 'gitops_cache',
    });
    this.cacheCleaner = new CacheCleaner(this.cacheDb);
    this.cacheCleaner.registerClass(CachedProject);

    this.opsServer = new OpsServer(this);
  }

  async start(port = 3000): Promise<void> {
    logger.info('Initializing GitOps...');

    // Start CacheDb
    await this.cacheDb.start();

    // Initialize connection manager (loads saved connections)
    await this.connectionManager.init();

    // Start CacheCleaner
    this.cacheCleaner.start();

    // Start OpsServer
    await this.opsServer.start(port);

    logger.success('GitOps initialized successfully');
  }

  async stop(): Promise<void> {
    logger.info('Shutting down GitOps...');
    await this.opsServer.stop();
    this.cacheCleaner.stop();
    await this.cacheDb.stop();
    logger.success('GitOps shutdown complete');
  }
}
