const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const AdmZip = require('adm-zip');

const cliDir = path.resolve(__dirname, '..');
const apiDir = path.resolve(__dirname, '../../../CAxFRAMEWORK/xframework-api');

if (!fs.existsSync(apiDir)) {
  console.error(`❌ API directory not found at: ${apiDir}`);
  process.exit(1);
}

const packageJson = JSON.parse(fs.readFileSync(path.join(cliDir, 'package.json'), 'utf8'));
const version = packageJson.version;

const distTemp = path.join(cliDir, 'dist-temp');
const releasesDir = path.join(cliDir, 'aws-releases', `v${version}`);

const platforms = [
  { runtime: 'win-x64', name: 'api-win-x64' },
  { runtime: 'osx-x64', name: 'api-mac-x64' },
  { runtime: 'linux-x64', name: 'api-linux-x64' }
];

const safeAppSettings = {
  AppName: 'ContentActive API',
  Logging: { LogLevel: { Default: 'Information', 'Microsoft.AspNetCore': 'Warning' } },
  AppSetup: { AppInstallRequired: true, AutoMigrate: false, Username: 'support@contentactive.com', Password: '', Role: 'System Admin' },
  Jwt: { ExpireDays: '1', Issuer: 'ContentActiveApi', Key: 'xframework-local-jwt-placeholder-key-min-32-chars!!', RefreshDays: '7' },
  LoginToken: { SecretKey: 'xframework-local-token-placeholder-key-min-32-chars!!' },
  SuperAdmin: 'Operation - Admin', DefaultRole: '797b6cf7-1a2f-4933-addb-33b4c51a87aa', DefaultRoleType: 'Operation', DefaultTenant: '8727CBE3-0560-477A-986A-055FEFEED749',
  EncryptKey: 'ReferralCode7443', TempTokenMinutes: 10, TempToken: { ExpireMinutes: '10' },
  Roles: { DefaultId: '797b6cf7-1a2f-4933-addb-33b4c51a87aa', DefaultType: 'Operation', CustomerRoleId: '3DD64000-A0CF-494B-B41E-5113CB92D22A' },
  RateLimiting: { Enabled: false },
  SecurityHeaders: { AddXFrameOptions: false, ReferrerPolicy: 'strict-origin-when-cross-origin', HstsEnabled: false, CspMode: 'frame-ancestors-only', CspReportUri: '/api/CspReport', PermissionsPolicy: 'geolocation=(), microphone=(), camera=(), payment=(), usb=()' },
  IdentityOptions: { Password: { RequiredLength: 6, RequireLowercase: false, RequireUppercase: false, RequireNonAlphanumeric: false, RequireDigit: false }, User: { RequireUniqueEmail: true, AllowedUserNameCharacters: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+' }, SignIn: { RequireConfirmedEmail: false }, Register: { RequireRegisterConfirmedEmail: false } },
  Cors: { AllowedOrigins: ['http://localhost:3000', 'http://localhost:5173', 'http://localhost:7125', 'http://localhost:7126', 'http://127.0.0.1:3000', 'http://127.0.0.1:5173', 'http://127.0.0.1:7125', 'http://127.0.0.1:7126'], AllowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'], AllowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'], AllowCredentials: true, PreflightMaxAge: 600, ExposedHeaders: ['Content-Disposition'] },
  BaseUrl: 'http://localhost:7125/', SiteUrl: '', Features: { SupportTickets: true },
  SupportTicketsValidation: { TitleMinLength: 3, TitleMaxLength: 200, DescriptionMaxLength: 2000, MessageMinLength: 1, MessageMaxLength: 2000, AttachmentMaxSizeBytes: 10485760, AllowedAttachmentTypes: ['.jpg', '.jpeg', '.png', '.gif', '.pdf', '.doc', '.docx', '.txt', '.zip'] },
  SupportTicketNotifications: { SupportTeamEmail: 'support@contentactive.com', CompanyName: 'ContentActive', SupportPortalUrl: 'http://localhost:7125/support', EnableNotifications: false, NotifyCustomers: false, NotifySupportTeam: false, NotifyOnStatusChange: false, NotifyOnNewMessage: false, NotifyOnResolution: false },
  DataRetention: { DefaultUserRetentionDays: 2555, DefaultAuditLogRetentionDays: 1825, DefaultSessionRetentionDays: 90, AnonymizationGracePeriodDays: 30, AutoScheduleInactiveUsers: true, InactivityThresholdDays: 1095, BackgroundProcessingEnabled: true, BackgroundProcessingIntervalMinutes: 1440, BatchSize: 1000, DefaultToDryRun: true },
  AISettings: { MaxRetries: 3 },
  AWSVideoSettings: { S3Settings: { VideoBucketName: '', ProcessedVideoBucketName: '', Region: 'us-east-1', AccessKey: '', SecretKey: '' }, LambdaSettings: { BackendApiKey: '' } },
  Aws: { AccessKeyId: '', SecretAccessKey: '', Bucket: '', IsAwsEnabled: 'False' },
  AzureBlobStorage: { ConnectionString: '', ContainerName: '' },
  AzureStorage: { ConnectionString: '', MemberPhotosContainer: '', BaseUrl: '' },
  AzureDocumentIntelligence: { Endpoint: '', Key: '' },
  CVSettings: { AzureVisionEndpoint: '', AzureVisionKey: '', ChunkSize: 1000, ChunkOverlap: 200, VectorDimensions: 1536 },
  FileManagement: { StorageProvider: 'Azure', MaxFileSizeBytes: 104857600, AllowedFileTypes: ['.jpg', '.jpeg', '.png', '.gif', '.pdf', '.doc', '.docx', '.txt', '.zip', '.csv', '.xlsx', '.mp4', '.mov', '.avi'], DefaultExpirationDays: 365, Azure: { ConnectionString: '', ContainerName: '', BaseUrl: '' }, AWS: { AccessKeyId: '', SecretAccessKey: '', BucketName: '', Region: 'us-east-1' } },
  Email: { From: '', SmtpServer: '', Port: 587, Username: '', Password: '' },
  Twilio: { AccountSid: '', AuthToken: '', VerifySID: '' }, TwilioConfiguration: { AccountSid: '', AuthToken: '', PhoneNumber: '' },
  PasswordLessAuth: { Domain: '', ClientId: '', ClientSecret: '' }, Vimeo: { VimeoToken: '', ClientId: '', ClientSecret: '', ExpireInMins: 20 },
  Stripe: { SecretKey: '', PublishableKey: '', WebhookSecret: '' }, OpenAIKey: '', Firebase: { CredentialsFile: '' },
  TwoFactorAuthentication: { DefaultMethod: 'Email' }, License: { Enabled: true }
};

function cleanup() {
  if (fs.existsSync(distTemp)) {
    fs.rmSync(distTemp, { recursive: true, force: true });
  }
}

try {
  cleanup();
  fs.mkdirSync(distTemp, { recursive: true });
  fs.mkdirSync(releasesDir, { recursive: true });

  console.log(`🚀 Building API v${version} for AWS S3...`);
  console.log(`📦 Output directory: ${releasesDir}\n`);

  for (const plat of platforms) {
    const outDir = path.join(distTemp, plat.name);
    console.log(`➡️ Compiling ${plat.runtime}...`);
    
    // 1. Run dotnet publish
    const result = spawnSync('dotnet', [
      'publish', 'XFramework.Api/XFramework.Api.csproj',
      '-c', 'Release', '-r', plat.runtime, 
      '--self-contained', 'true', '/p:PublishSingleFile=true', '/p:UseAppHost=true', '-o', outDir
    ], { cwd: apiDir, stdio: 'inherit' });

    if (result.status !== 0) {
      console.error(`❌ Build failed for ${plat.runtime}`);
      process.exit(1);
    }

    // 2. Strip AppSettings
    console.log(`   Stripping credentials from appsettings.json...`);
    fs.writeFileSync(path.join(outDir, 'appsettings.json'), JSON.stringify(safeAppSettings, null, 2));

    // Also remove any dev/local settings and private credential files just in case
    for (const file of fs.readdirSync(outDir)) {
      const lower = file.toLowerCase();
      if (
        lower === 'appsettings.development.json' || 
        lower === 'appsettings.local.json' ||
        (lower.includes('firebase') && lower.endsWith('.json')) || 
        (lower.includes('adminsdk') && lower.endsWith('.json')) || 
        lower.endsWith('.key')
      ) {
        fs.unlinkSync(path.join(outDir, file));
        console.log(`   Removed sensitive file: ${file}`);
      }
    }

    // 3. Zip it up
    console.log(`   Zipping ${plat.name}.zip...`);
    const zip = new AdmZip();
    zip.addLocalFolder(outDir);
    const zipPath = path.join(releasesDir, `${plat.name}.zip`);
    zip.writeZip(zipPath);

    console.log(`   ✅ Created ${zipPath}\n`);
  }

  console.log(`🎉 All builds completed successfully!`);
  console.log(`📤 You can now upload the contents of:`);
  console.log(`   ${releasesDir}`);
  console.log(`   to your AWS S3 bucket.`);

} catch (err) {
  console.error('❌ Error during build:', err);
  process.exit(1);
} finally {
  cleanup();
}
