const fs = require('fs');
const path = require('path');

const filePath = 'apps/api/src/domain/league/dtos/LeagueDto.ts';
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.split('\n');

let allImports = lines.filter(line => line.startsWith('import '));

let classBlocks = [];
let currentClassLines = [];
let inClass = false;

for (let i = 0; i < lines.length; i++) {
  let line = lines[i];
  if (line.startsWith('export class ')) {
    if (inClass) {
      classBlocks.push(currentClassLines);
      currentClassLines = [];
    }
    inClass = true;
  }
  if (inClass) {
    currentClassLines.push(line);
    if (line.trim() === '}') {
      classBlocks.push(currentClassLines);
      currentClassLines = [];
      inClass = false;
    }
  }
}

if (currentClassLines.length > 0) {
  classBlocks.push(currentClassLines);
}

// Function to get imports for class
function getImportsForClass(classLines, className) {
  let classContent = classLines.join('\n');
  let neededImports = [];

  // ApiProperty
  if (classContent.includes('@ApiProperty')) {
    neededImports.push("import { ApiProperty } from '@nestjs/swagger';");
  }

  // class-validator
  let validators = [];
  if (classContent.includes('@IsString')) validators.push('IsString');
  if (classContent.includes('@IsNumber')) validators.push('IsNumber');
  if (classContent.includes('@IsBoolean')) validators.push('IsBoolean');
  if (classContent.includes('@IsDate')) validators.push('IsDate');
  if (classContent.includes('@IsOptional')) validators.push('IsOptional');
  if (classContent.includes('@IsEnum')) validators.push('IsEnum');
  if (classContent.includes('@IsArray')) validators.push('IsArray');
  if (classContent.includes('@ValidateNested')) validators.push('ValidateNested');
  if (validators.length > 0) {
    neededImports.push(`import { ${validators.join(', ')} } from 'class-validator';`);
  }

  // class-transformer
  if (classContent.includes('@Type')) {
    neededImports.push("import { Type } from 'class-transformer';");
  }

  // Other DTOs
  if (classContent.includes('DriverDto')) {
    neededImports.push("import { DriverDto } from '../../driver/dto/DriverDto';");
  }
  if (classContent.includes('RaceDto')) {
    neededImports.push("import { RaceDto } from '../../race/dto/RaceDto';");
  }

  // Local DTOs
  let localDTOs = ['LeagueSettingsDTO', 'LeagueWithCapacityDTO', 'LeagueSummaryDTO', 'AllLeaguesWithCapacityDTO', 'AllLeaguesWithCapacityAndScoringDTO', 'LeagueStatsDTO', 'ProtestDTO', 'SeasonDTO', 'LeagueJoinRequestDTO', 'GetLeagueJoinRequestsQueryDTO', 'ApproveJoinRequestInputDTO', 'ApproveJoinRequestOutputDTO', 'RejectJoinRequestInputDTO', 'RejectJoinRequestOutputDTO', 'GetLeagueAdminPermissionsInputDTO', 'LeagueAdminPermissionsDTO', 'RemoveLeagueMemberInputDTO', 'RemoveLeagueMemberOutputDTO', 'UpdateLeagueMemberRoleInputDTO', 'UpdateLeagueMemberRoleOutputDTO', 'GetLeagueOwnerSummaryQueryDTO', 'LeagueOwnerSummaryDTO', 'LeagueConfigFormModelBasicsDTO', 'LeagueConfigFormModelStructureDTO', 'LeagueConfigFormModelScoringDTO', 'LeagueConfigFormModelDropPolicyDTO', 'LeagueConfigFormModelStewardingDTO', 'LeagueConfigFormModelTimingsDTO', 'LeagueConfigFormModelDTO', 'GetLeagueAdminConfigQueryDTO', 'GetLeagueAdminConfigOutputDTO', 'LeagueAdminConfigDTO', 'GetLeagueProtestsQueryDTO', 'LeagueAdminProtestsDTO', 'GetLeagueSeasonsQueryDTO', 'LeagueSeasonSummaryDTO', 'LeagueAdminDTO', 'LeagueMemberDTO', 'LeagueMembershipsDTO', 'LeagueStandingDTO', 'LeagueStandingsDTO', 'LeagueScheduleDTO', 'LeagueStatsDTO', 'CreateLeagueInputDTO', 'CreateLeagueOutputDTO'];

  for (let dto of localDTOs) {
    if (dto !== className && classContent.includes(dto)) {
      neededImports.push(`import { ${dto} } from './${dto}';`);
    }
  }

  return neededImports;
}

for (let classLines of classBlocks) {
  let classNameLine = classLines.find(line => line.startsWith('export class '));
  if (classNameLine) {
    let match = classNameLine.match(/export class (\w+)/);
    if (match) {
      let className = match[1];
      // Rename
      if (className.endsWith('ViewModel')) {
        className = className.replace('ViewModel', 'DTO');
      } else if (className.endsWith('Dto')) {
        className = className.replace('Dto', 'DTO');
      } else if (className.endsWith('Input')) {
        className = className + 'DTO';
      } else if (className.endsWith('Output')) {
        className = className + 'DTO';
      } else if (className.endsWith('Query')) {
        className = className + 'DTO';
      } else {
        className = className + 'DTO';
      }
      let fileName = className + '.ts';
      // Update class name in lines
      classLines[0] = classLines[0].replace(/export class \w+/, 'export class ' + className);
      // Update references in the class
      for (let i = 1; i < classLines.length; i++) {
        classLines[i] = classLines[i].replace(/ViewModel/g, 'DTO').replace(/Dto/g, 'DTO').replace(/Input\b/g, 'InputDTO').replace(/Output\b/g, 'OutputDTO').replace(/Query\b/g, 'QueryDTO');
        classLines[i] = classLines[i].replace(/DriverDTO/g, 'DriverDto').replace(/RaceDTO/g, 'RaceDto');
      }
      let imports = getImportsForClass(classLines, className);
      let fileContent = imports.join('\n') + '\n\n' + classLines.join('\n');
      fs.writeFileSync(path.join('apps/api/src/domain/league/dtos', fileName), fileContent);
    }
  }
}