import 'dart:io';
import '../logging/logger.dart';

class DashboardBuilder {
  static const String _dashboardPath = '../xp_dashboard';
  static const String _buildOutputPath = '../xp_dashboard/build/web';
  static const String _staticPath = 'lib/src/web/static';

  /// Builds the Flutter dashboard and copies files to the static directory
  static Future<bool> buildDashboard() async {
    try {
      Logger.info('Starting Flutter dashboard build...');
      print('🔨 Building Flutter dashboard...');

      // Check if dashboard directory exists
      final dashboardDir = Directory(_dashboardPath);
      if (!await dashboardDir.exists()) {
        Logger.error('Dashboard directory not found: $_dashboardPath');
        print('❌ Dashboard directory not found: $_dashboardPath');
        return false;
      }

      // Run flutter build web
      final buildResult = await Process.run(
        'flutter',
        ['build', 'web', '--release'],
        workingDirectory: _dashboardPath,
      );

      if (buildResult.exitCode != 0) {
        Logger.error('Flutter build failed: ${buildResult.stderr}');
        print('❌ Flutter build failed:');
        print(buildResult.stderr);
        return false;
      }

      Logger.info('Flutter build completed successfully');
      print('✅ Flutter build completed');

      // Check if build output exists
      final buildDir = Directory(_buildOutputPath);
      if (!await buildDir.exists()) {
        Logger.error('Build output directory not found: $_buildOutputPath');
        print('❌ Build output directory not found: $_buildOutputPath');
        return false;
      }

      // Copy files to static directory
      await _copyBuildFiles();

      Logger.info('Dashboard build and copy completed successfully');
      print('✅ Dashboard files copied to static directory');
      return true;

    } catch (e) {
      Logger.error('Error building dashboard: $e');
      print('❌ Error building dashboard: $e');
      return false;
    }
  }

  /// Copies built Flutter web files to the static directory
  static Future<void> _copyBuildFiles() async {
    final buildDir = Directory(_buildOutputPath);
    final staticDir = Directory(_staticPath);

    // Create static directory if it doesn't exist
    if (!await staticDir.exists()) {
      await staticDir.create(recursive: true);
    }

    // Clear existing static files (except for any non-Flutter files we want to keep)
    await _clearStaticDirectory();

    // Copy all files from build/web to static
    await _copyDirectory(buildDir, staticDir);
  }

  /// Clears the static directory of old files
  static Future<void> _clearStaticDirectory() async {
    final staticDir = Directory(_staticPath);
    if (!await staticDir.exists()) return;

    await for (final entity in staticDir.list()) {
      if (entity is File) {
        await entity.delete();
      } else if (entity is Directory) {
        await entity.delete(recursive: true);
      }
    }
  }

  /// Recursively copies a directory
  static Future<void> _copyDirectory(Directory source, Directory destination) async {
    await for (final entity in source.list(recursive: false)) {
      if (entity is File) {
        final relativePath = entity.path.substring(source.path.length + 1);
        final destFile = File('${destination.path}/$relativePath');
        
        // Create parent directories if needed
        await destFile.parent.create(recursive: true);
        await entity.copy(destFile.path);
        
      } else if (entity is Directory) {
        final relativePath = entity.path.substring(source.path.length + 1);
        final destDir = Directory('${destination.path}/$relativePath');
        await destDir.create(recursive: true);
        await _copyDirectory(entity, destDir);
      }
    }
  }

  /// Checks if Flutter is available in the system
  static Future<bool> checkFlutterAvailable() async {
    try {
      final result = await Process.run('flutter', ['--version']);
      return result.exitCode == 0;
    } catch (e) {
      return false;
    }
  }
}
