All files / blacktrigram fixprops.ts

0% Statements 0/569
100% Branches 1/1
100% Functions 1/1
0% Lines 0/569

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
// 0. Imports and bootstrap
import * as fs from "fs";
import * as path from "path";
import {
  ImportDeclaration,
  InterfaceDeclaration,
  Project,
  SourceFile,
  TypeAliasDeclaration,
} from "ts-morph";
 
const project = new Project({ tsConfigFilePath: "tsconfig.json" });
 
// Enhanced configuration with validation
const CONFIG = {
  // All types files that contain Props
  propsTypeFiles: [
    "src/types/components.ts",
    "src/types/ui.ts",
    "src/types/combat.ts",
    "src/types/game.ts",
  ],
 
  // Base interfaces to keep in types (not Props themselves)
  keepInTypes: [
    "BaseComponentProps",
    "BaseUIProps",
    "UIComponentProps",
  ] as const,
 
  // Component mapping patterns with validation
  componentMapping: {
    // Screen components
    IntroScreenProps: "src/components/intro/IntroScreen.tsx",
    TrainingScreenProps: "src/components/training/TrainingScreen.tsx",
    CombatScreenProps: "src/components/combat/CombatScreen.tsx",
    EndScreenProps: "src/components/ui/EndScreen.tsx",
    LoadingScreenProps: "src/components/ui/LoadingScreen.tsx",
    MainMenuScreenProps: "src/components/ui/MainMenuScreen.tsx",
    SettingsScreenProps: "src/components/ui/SettingsScreen.tsx",
 
    // Combat components
    CombatArenaProps: "src/components/combat/components/CombatArena.tsx",
    CombatHUDProps: "src/components/combat/components/CombatHUD.tsx",
    CombatControlsProps: "src/components/combat/components/CombatControls.tsx",
    PlayerStatusPanelProps:
      "src/components/combat/components/PlayerStatusPanel.tsx",
    CombatStatsProps: "src/components/combat/components/CombatStats.tsx",
 
    // UI components
    HealthBarProps: "src/components/ui/HealthBar.tsx",
    StanceIndicatorProps: "src/components/ui/StanceIndicator.tsx",
    TrigramWheelProps: "src/components/ui/TrigramWheel.tsx",
    ProgressTrackerProps: "src/components/ui/ProgressTracker.tsx",
    ScoreDisplayProps: "src/components/ui/ScoreDisplay.tsx",
    RoundTimerProps: "src/components/ui/RoundTimer.tsx",
    KoreanHeaderProps: "src/components/ui/KoreanHeader.tsx",
 
    // Game components
    PlayerProps: "src/components/game/Player.tsx",
    PlayerVisualsProps: "src/components/game/PlayerVisuals.tsx",
    DojangBackgroundProps: "src/components/game/DojangBackground.tsx",
    HitEffectsLayerProps: "src/components/game/HitEffectsLayer.tsx",
    GameEngineProps: "src/components/game/GameEngine.tsx",
 
    // Intro components
    MenuSectionProps: "src/components/intro/components/MenuSection.tsx",
    ControlsSectionProps: "src/components/intro/components/ControlsSection.tsx",
    ArchetypeDisplayProps:
      "src/components/intro/components/ArchetypeDisplay.tsx",
    PhilosophySectionProps:
      "src/components/intro/components/PhilosophySection.tsx",
 
    // Audio
    AudioProviderProps: "src/audio/AudioProvider.tsx",
 
    // Specialized UI
    TrainingModeUIProps: "src/components/training/TrainingModeUI.tsx",
    VictoryPoseScreenProps: "src/components/ui/VictoryPoseScreen.tsx",
    VitalPointDisplayProps: "src/components/ui/VitalPointDisplay.tsx",
    ModalProps: "src/components/ui/base/Modal.tsx",
    BaseButtonProps: "src/components/ui/base/BaseButton.tsx",
    GameUIProps: "src/components/ui/GameUI.tsx",
  } as const,
 
  // Enhanced import detection patterns
  typePatterns: [
    // Korean martial arts types
    /\b(PlayerArchetype|TrigramStance|KoreanText|VitalPoint)\b/g,
    // Combat types
    /\b(CombatAttackType|DamageType|HitEffect|GameMode)\b/g,
    // UI types
    /\b(PlayerState|BaseComponentProps|BaseUIProps|UIComponentProps)\b/g,
    // Game types
    /\b(AudioSettings|GameSettings|ControlSettings)\b/g,
  ],
 
  // Backup settings
  createBackup: true,
  backupDir: ".backup-props",
  dryRun: false, // Set to true for testing
} as const;
 
// Helper type for the keepInTypes array
type KeepInTypesType = (typeof CONFIG.keepInTypes)[number];
 
interface PropsInfo {
  readonly name: string;
  readonly filePath: string;
  readonly targetPath: string;
  readonly definition: InterfaceDeclaration | TypeAliasDeclaration;
  readonly extends: readonly string[];
  readonly imports: readonly string[];
  readonly hasJSDoc: boolean;
  readonly complexity: number;
}
 
interface MigrationStats {
  found: number;
  moved: number;
  deleted: number;
  filesUpdated: number;
  errors: string[];
  warnings: string[];
}
 
class PropsMigrator {
  private stats: MigrationStats = {
    found: 0,
    moved: 0,
    deleted: 0,
    filesUpdated: 0,
    errors: [],
    warnings: [],
  };
 
  private readonly project: Project;
 
  constructor(project: Project) {
    this.project = project;
  }
 
  async migrate(): Promise<MigrationStats> {
    console.log("๐Ÿš€ Starting Props migration with enhanced validation...\n");
 
    try {
      // Validate configuration
      await this.validateConfiguration();
 
      // Create backup if enabled
      if (CONFIG.createBackup) {
        await this.createBackup();
      }
 
      // Main migration steps
      const propsMap = await this.scanPropsInterfaces();
      await this.validateTargetFiles(propsMap);
      await this.movePropsToComponents(propsMap);
      await this.updateImportsGlobally(propsMap);
      await this.cleanupTypeFiles();
      await this.validateMigration();
 
      this.printSummary();
      return this.stats;
    } catch (error) {
      console.error(`โŒ Migration failed: ${error.message}`);
      this.stats.errors.push(error.message);
      throw error;
    }
  }
 
  private async validateConfiguration(): Promise<void> {
    console.log("๐Ÿ” Validating configuration...");
 
    // Check if type files exist
    for (const filePath of CONFIG.propsTypeFiles) {
      if (!fs.existsSync(filePath)) {
        const error = `Type file not found: ${filePath}`;
        this.stats.errors.push(error);
        throw new Error(error);
      }
    }
 
    // Validate component mapping paths
    const invalidPaths: string[] = [];
    for (const [propsName, componentPath] of Object.entries(
      CONFIG.componentMapping
    )) {
      if (!fs.existsSync(componentPath)) {
        invalidPaths.push(`${propsName} โ†’ ${componentPath}`);
        this.stats.warnings.push(`Component file not found: ${componentPath}`);
      }
    }
 
    if (invalidPaths.length > 0) {
      console.warn(
        `   โš ๏ธ  Found ${invalidPaths.length} invalid component paths:`
      );
      invalidPaths.forEach((path) => console.warn(`      ${path}`));
    }
 
    console.log("   โœ… Configuration validated\n");
  }
 
  private async createBackup(): Promise<void> {
    console.log("๐Ÿ’พ Creating backup...");
 
    if (!fs.existsSync(CONFIG.backupDir)) {
      fs.mkdirSync(CONFIG.backupDir, { recursive: true });
    }
 
    const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
    const backupPath = path.join(CONFIG.backupDir, `backup-${timestamp}`);
    fs.mkdirSync(backupPath, { recursive: true });
 
    // Backup type files
    for (const filePath of CONFIG.propsTypeFiles) {
      if (fs.existsSync(filePath)) {
        const backupFile = path.join(backupPath, path.basename(filePath));
        fs.copyFileSync(filePath, backupFile);
      }
    }
 
    console.log(`   โœ… Backup created at ${backupPath}\n`);
  }
 
  private async scanPropsInterfaces(): Promise<Map<string, PropsInfo>> {
    console.log("๐Ÿ“‹ Scanning Props interfaces with enhanced analysis...");
    const propsMap = new Map<string, PropsInfo>();
 
    for (const filePath of CONFIG.propsTypeFiles) {
      const file = this.project.getSourceFile(filePath);
      if (!file) continue;
 
      console.log(`   Scanning ${filePath}...`);
 
      // Scan interfaces
      for (const intf of file.getInterfaces()) {
        const info = this.analyzePropsInterface(intf, filePath);
        if (info) {
          propsMap.set(info.name, info);
          console.log(
            `     Found interface: ${info.name} (complexity: ${info.complexity})`
          );
        }
      }
 
      // Scan type aliases
      for (const alias of file.getTypeAliases()) {
        const info = this.analyzePropsTypeAlias(alias, filePath);
        if (info) {
          propsMap.set(info.name, info);
          console.log(
            `     Found type alias: ${info.name} (complexity: ${info.complexity})`
          );
        }
      }
    }
 
    this.stats.found = propsMap.size;
    console.log(`   โœ… Found ${propsMap.size} Props definitions\n`);
    return propsMap;
  }
 
  private analyzePropsInterface(
    intf: InterfaceDeclaration,
    filePath: string
  ): PropsInfo | null {
    const name = intf.getName();
 
    if (!name.endsWith("Props") || this.isKeepInTypes(name)) {
      return null;
    }
 
    const targetPath =
      CONFIG.componentMapping[name as keyof typeof CONFIG.componentMapping];
    if (!targetPath) {
      this.stats.warnings.push(`No mapping found for ${name}`);
      return null;
    }
 
    const definitionText = intf.getFullText();
    const imports = this.extractRequiredImports(definitionText);
    const complexity = this.calculateComplexity(intf);
 
    return {
      name,
      filePath,
      targetPath,
      definition: intf,
      extends: intf.getExtends().map((e) => e.getText()),
      imports,
      hasJSDoc: intf.getJsDocs().length > 0,
      complexity,
    };
  }
 
  private analyzePropsTypeAlias(
    alias: TypeAliasDeclaration,
    filePath: string
  ): PropsInfo | null {
    const name = alias.getName();
 
    if (!name.endsWith("Props") || this.isKeepInTypes(name)) {
      return null;
    }
 
    const targetPath =
      CONFIG.componentMapping[name as keyof typeof CONFIG.componentMapping];
    if (!targetPath) {
      this.stats.warnings.push(`No mapping found for ${name}`);
      return null;
    }
 
    const definitionText = alias.getFullText();
    const imports = this.extractRequiredImports(definitionText);
    const complexity = this.calculateComplexity(alias);
 
    return {
      name,
      filePath,
      targetPath,
      definition: alias,
      extends: [],
      imports,
      hasJSDoc: alias.getJsDocs().length > 0,
      complexity,
    };
  }
 
  // Helper method to check if a type should be kept in types
  private isKeepInTypes(name: string): name is KeepInTypesType {
    return (CONFIG.keepInTypes as readonly string[]).includes(name);
  }
 
  private extractRequiredImports(definitionText: string): string[] {
    const imports = new Set<string>();
 
    // Apply all type patterns to find imports
    for (const pattern of CONFIG.typePatterns) {
      const matches = definitionText.match(pattern);
      if (matches) {
        matches.forEach((match) => imports.add(match));
      }
    }
 
    return Array.from(imports);
  }
 
  private calculateComplexity(
    node: InterfaceDeclaration | TypeAliasDeclaration
  ): number {
    // Simple complexity calculation based on:
    // - Number of properties/type complexity
    // - Number of extends/unions
    // - Presence of generics
    // - JSDoc comments
 
    let complexity = 1;
 
    if (node instanceof InterfaceDeclaration) {
      complexity += node.getProperties().length;
      complexity += node.getExtends().length * 2;
      complexity += node.getTypeParameters().length;
    } else {
      const typeText = node.getTypeNode()?.getText() || "";
      complexity += (typeText.match(/[&|]/g) || []).length; // Union/intersection types
      complexity += (typeText.match(/</g) || []).length; // Generics
    }
 
    complexity += node.getJsDocs().length;
    return complexity;
  }
 
  private async validateTargetFiles(
    propsMap: Map<string, PropsInfo>
  ): Promise<void> {
    console.log("๐Ÿ” Validating target component files...");
 
    for (const [propsName, info] of propsMap) {
      const targetFile = this.project.getSourceFile(info.targetPath);
 
      if (!targetFile) {
        this.stats.warnings.push(`Target file not found: ${info.targetPath}`);
        continue;
      }
 
      // Check if Props already exists
      const existing =
        targetFile.getInterface(propsName) ||
        targetFile.getTypeAlias(propsName);
      if (existing) {
        console.log(`   โœ… ${propsName} already exists in ${info.targetPath}`);
      }
    }
 
    console.log("   โœ… Target file validation complete\n");
  }
 
  private async movePropsToComponents(
    propsMap: Map<string, PropsInfo>
  ): Promise<void> {
    console.log(
      "๐Ÿšš Moving Props to component files with enhanced import handling..."
    );
 
    for (const [propsName, info] of propsMap) {
      if (CONFIG.dryRun) {
        console.log(
          `   [DRY RUN] Would move ${propsName} to ${info.targetPath}`
        );
        continue;
      }
 
      try {
        const success = await this.movePropsToFile(info);
        if (success) {
          this.stats.moved++;
          console.log(`   โœ… Moved ${propsName} to ${info.targetPath}`);
        } else {
          this.stats.warnings.push(`Failed to move ${propsName}`);
        }
      } catch (error) {
        const errorMsg = `Failed to move ${propsName}: ${error.message}`;
        this.stats.errors.push(errorMsg);
        console.error(`   โŒ ${errorMsg}`);
      }
    }
 
    console.log(`   โœ… Moved ${this.stats.moved} Props definitions\n`);
  }
 
  private async movePropsToFile(info: PropsInfo): Promise<boolean> {
    const targetFile = this.project.getSourceFile(info.targetPath);
    if (!targetFile) return false;
 
    // Check if already exists
    const existing =
      targetFile.getInterface(info.name) || targetFile.getTypeAlias(info.name);
    if (existing) return true;
 
    // Add required imports
    await this.addRequiredImports(targetFile, info.imports);
 
    // Add the definition
    if (info.definition instanceof InterfaceDeclaration) {
      await this.addInterfaceToFile(targetFile, info.definition);
    } else {
      await this.addTypeAliasToFile(targetFile, info.definition);
    }
 
    targetFile.saveSync();
    return true;
  }
 
  private async addRequiredImports(
    targetFile: SourceFile,
    requiredImports: readonly string[]
  ): Promise<void> {
    if (requiredImports.length === 0) return;
 
    // Find existing types import
    const existingTypesImport = targetFile.getImportDeclaration((decl) =>
      decl.getModuleSpecifierValue().includes("/types")
    );
 
    if (existingTypesImport) {
      // Add to existing import
      const currentImports = existingTypesImport
        .getNamedImports()
        .map((imp) => imp.getName());
      const newImports = requiredImports.filter(
        (imp) => !currentImports.includes(imp)
      );
 
      if (newImports.length > 0) {
        existingTypesImport.addNamedImports(newImports);
      }
    } else {
      // Create new import
      const relativePath = this.calculateRelativePath(
        targetFile.getFilePath(),
        "src/types"
      );
      targetFile.addImportDeclaration({
        isTypeOnly: true,
        moduleSpecifier: relativePath,
        namedImports: Array.from(requiredImports),
      });
    }
  }
 
  private async addInterfaceToFile(
    targetFile: SourceFile,
    intf: InterfaceDeclaration
  ): Promise<void> {
    targetFile.addInterface({
      isExported: true,
      name: intf.getName(),
      extends: intf.getExtends().map((e) => e.getText()),
      properties: intf.getProperties().map((prop) => ({
        name: prop.getName(),
        type: prop.getTypeNode()?.getText() || "any",
        hasQuestionToken: prop.hasQuestionToken(),
        docs: prop.getJsDocs().map((doc) => doc.getDescription()),
      })),
      docs: intf.getJsDocs().map((doc) => doc.getDescription()),
      typeParameters: intf.getTypeParameters().map((tp) => ({
        name: tp.getName(),
        constraint: tp.getConstraint()?.getText(),
        default: tp.getDefault()?.getText(),
      })),
    });
  }
 
  private async addTypeAliasToFile(
    targetFile: SourceFile,
    alias: TypeAliasDeclaration
  ): Promise<void> {
    targetFile.addTypeAlias({
      isExported: true,
      name: alias.getName(),
      type: alias.getTypeNode()?.getText() || "any",
      docs: alias.getJsDocs().map((doc) => doc.getDescription()),
      typeParameters: alias.getTypeParameters().map((tp) => ({
        name: tp.getName(),
        constraint: tp.getConstraint()?.getText(),
        default: tp.getDefault()?.getText(),
      })),
    });
  }
 
  private calculateRelativePath(fromFile: string, toDir: string): string {
    const relativePath = path
      .relative(path.dirname(fromFile), toDir)
      .replace(/\\/g, "/");
 
    return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
  }
 
  private async updateImportsGlobally(
    propsMap: Map<string, PropsInfo>
  ): Promise<void> {
    console.log("๐Ÿ”— Updating imports throughout codebase...");
 
    const allFiles = this.project.getSourceFiles("src/**/*.{ts,tsx}");
 
    for (const file of allFiles) {
      let changed = false;
 
      for (const importDecl of file.getImportDeclarations()) {
        const moduleSpecifier = importDecl.getModuleSpecifierValue();
        if (!moduleSpecifier.includes("/types")) continue;
 
        const namedImports = importDecl.getNamedImports();
        const propsImports = namedImports.filter((imp) => {
          const name = imp.getName();
          return name.endsWith("Props") && propsMap.has(name);
        });
 
        if (propsImports.length === 0) continue;
 
        // Create new imports for each Props
        for (const propsImport of propsImports) {
          const propsName = propsImport.getName();
          const propsInfo = propsMap.get(propsName);
          if (!propsInfo) continue;
 
          const relativePath = this.calculateRelativePath(
            file.getFilePath(),
            propsInfo.targetPath.replace(/\.(tsx?)$/, "")
          );
 
          // Add new import
          file.addImportDeclaration({
            isTypeOnly: true,
            moduleSpecifier: relativePath,
            namedImports: [propsName],
          });
 
          propsImport.remove();
          changed = true;
        }
 
        // Remove empty import declarations
        if (this.isEmptyImport(importDecl)) {
          importDecl.remove();
          changed = true;
        }
      }
 
      if (changed) {
        if (!CONFIG.dryRun) {
          file.saveSync();
        }
        this.stats.filesUpdated++;
      }
    }
 
    console.log(`   โœ… Updated imports in ${this.stats.filesUpdated} files\n`);
  }
 
  private isEmptyImport(importDecl: ImportDeclaration): boolean {
    return (
      importDecl.getNamedImports().length === 0 &&
      !importDecl.getDefaultImport() &&
      !importDecl.getNamespaceImport()
    );
  }
 
  private async cleanupTypeFiles(): Promise<void> {
    console.log("๐Ÿงน Cleaning up type files...");
 
    // Delete moved Props from type files
    for (const filePath of CONFIG.propsTypeFiles) {
      const file = this.project.getSourceFile(filePath);
      if (!file) continue;
 
      let deletedCount = 0;
 
      // Delete interfaces
      for (const intf of file.getInterfaces()) {
        const name = intf.getName();
        if (name.endsWith("Props") && !this.isKeepInTypes(name)) {
          if (!CONFIG.dryRun) {
            intf.remove();
          }
          deletedCount++;
        }
      }
 
      // Delete type aliases
      for (const alias of file.getTypeAliases()) {
        const name = alias.getName();
        if (name.endsWith("Props") && !this.isKeepInTypes(name)) {
          if (!CONFIG.dryRun) {
            alias.remove();
          }
          deletedCount++;
        }
      }
 
      if (deletedCount > 0) {
        if (!CONFIG.dryRun) {
          file.saveSync();
        }
        this.stats.deleted += deletedCount;
        console.log(`   ๐Ÿ—‘๏ธ  Cleaned up ${deletedCount} Props from ${filePath}`);
      }
    }
 
    // Clean up barrel exports
    await this.cleanupBarrelExports();
 
    console.log(`   โœ… Deleted ${this.stats.deleted} Props from type files\n`);
  }
 
  private async cleanupBarrelExports(): Promise<void> {
    const indexBarrel = this.project.getSourceFile("src/types/index.ts");
    if (!indexBarrel) return;
 
    let cleaned = false;
 
    for (const exportDecl of indexBarrel.getExportDeclarations()) {
      const namedExports = exportDecl.getNamedExports();
      const propsExports = namedExports.filter(
        (e) => e.getName().endsWith("Props") && !this.isKeepInTypes(e.getName())
      );
 
      if (
        propsExports.length === namedExports.length &&
        propsExports.length > 0
      ) {
        // Remove entire export if only Props
        if (!CONFIG.dryRun) {
          exportDecl.remove();
        }
        cleaned = true;
      } else if (propsExports.length > 0) {
        // Remove only Props exports
        if (!CONFIG.dryRun) {
          propsExports.forEach((e) => e.remove());
        }
        cleaned = true;
      }
    }
 
    if (cleaned && !CONFIG.dryRun) {
      indexBarrel.saveSync();
    }
  }
 
  private async validateMigration(): Promise<void> {
    console.log("โœ… Validating migration results...");
 
    // Check that all moved Props can be imported from their new locations
    for (const [propsName, targetPath] of Object.entries(
      CONFIG.componentMapping
    )) {
      const targetFile = this.project.getSourceFile(targetPath);
      if (!targetFile) continue;
 
      const hasInterface = !!targetFile.getInterface(propsName);
      const hasTypeAlias = !!targetFile.getTypeAlias(propsName);
 
      if (!hasInterface && !hasTypeAlias) {
        this.stats.warnings.push(
          `${propsName} not found in ${targetPath} after migration`
        );
      }
    }
 
    console.log("   โœ… Migration validation complete\n");
  }
 
  private printSummary(): void {
    console.log("๐Ÿ“Š Enhanced Migration Summary:");
    console.log(`   โ€ข Props interfaces found: ${this.stats.found}`);
    console.log(`   โ€ข Props interfaces moved: ${this.stats.moved}`);
    console.log(`   โ€ข Props interfaces deleted: ${this.stats.deleted}`);
    console.log(`   โ€ข Files with updated imports: ${this.stats.filesUpdated}`);
    console.log(`   โ€ข Type files processed: ${CONFIG.propsTypeFiles.length}`);
    console.log(`   โ€ข Errors encountered: ${this.stats.errors.length}`);
    console.log(`   โ€ข Warnings generated: ${this.stats.warnings.length}`);
 
    if (this.stats.errors.length > 0) {
      console.log("\nโŒ Errors:");
      this.stats.errors.forEach((error) => console.log(`   โ€ข ${error}`));
    }
 
    if (this.stats.warnings.length > 0) {
      console.log("\nโš ๏ธ  Warnings:");
      this.stats.warnings.forEach((warning) => console.log(`   โ€ข ${warning}`));
    }
 
    if (CONFIG.dryRun) {
      console.log("\n๐Ÿงช DRY RUN MODE - No files were actually modified");
    }
 
    const success =
      this.stats.errors.length === 0 && this.stats.moved === this.stats.found;
    console.log(
      `\n${success ? "โœ…" : "โš ๏ธ"} Enhanced fixprops.ts completed ${
        success ? "successfully" : "with issues"
      }!`
    );
  }
}
 
// Execute the migration
async function main(): Promise<void> {
  const migrator = new PropsMigrator(project);
 
  try {
    await migrator.migrate();
    process.exit(0);
  } catch (error) {
    console.error("Migration failed:", error);
    process.exit(1);
  }
}
 
// Run if this file is executed directly (ES module compatible)
const isMainModule = process.argv[1] === new URL(import.meta.url).pathname;
if (isMainModule) {
  main().catch(console.error);
}
 
export { CONFIG, PropsMigrator };