<?php
/**
 * ============================================================================
 * Class: SftcyWordaiClassmapGenerator
 * File:  /includes/class-sftcy-wordai-classmap-generator.php
 * ============================================================================
 * PURPOSE:
 * - Scans all class files under /includes/ matching "class-sftcy-wordai-*.php"
 * - Detects class declarations (ignores comments)
 * - Marks classes with __construct() for auto-bootstrap
 * - Generates classmap.json with plugin name, version, timestamp
 * - Auto-regenerates silently on activation/version change
 *
 * NOTE:
 * ⚠️ AUTO-GENERATED FILE. DO NOT EDIT classmap.json MANUALLY.
 * It will regenerate if deleted, corrupted, or plugin version changes.
 * ============================================================================
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'SftcyWordaiClassmapGenerator' ) ) {

	class SftcyWordaiClassmapGenerator {

		/**
		 * Generate and save classmap.json
		 */
		public static function generate() {

			// Get plugin header data safely
			$plugin_data = get_file_data(
				SFTCY_WORDAI_PLUGIN_FILE,
				array(
					'Name'    => 'Plugin Name',
					'Version' => 'Version',
				)
			);

			$plugin_name    = $plugin_data['Name'] ?? 'WordAI Pro';
			$plugin_version = $plugin_data['Version'] ?? SFTCY_WORDAI_VERSION;

			$classmap = [
				'_comment'       => sprintf(
					'⚠️ AUTO-GENERATED BY %s — DO NOT EDIT MANUALLY. This file regenerates automatically when deleted, corrupted, or version changes.',
					$plugin_name
				),
				'plugin_name'    => $plugin_name,
				'version'        => $plugin_version,
				'generated_at'   => current_time( 'mysql' ),
				'classes'        => [],
				'bootstrap'      => [],
			];

			// Scan includes/
			$files = glob( SFTCY_WORDAI_PLUGIN_INC . 'class-sftcy-wordai-*.php' );

			foreach ( $files as $file ) {
				$basename = basename( $file );

				// Skip backup/temporary
				if ( preg_match( '/\.php\.[^\/]+$/', $basename ) || str_ends_with( $basename, '.back.php' ) || str_ends_with( $basename, '.backup.php' ) ) {
					continue;
				}

				$contents = file_get_contents( $file );
				if ( ! $contents ) {
					continue;
				}

				// Extract real class name
				if ( preg_match( '/^[ \t]*class\s+([A-Za-z0-9_]+)/m', $contents, $matches ) ) {
					$class_name = trim( $matches[1] );
					$key        = strtolower( $class_name );

					$classmap['classes'][ $key ] = str_replace( SFTCY_WORDAI_PLUGIN_DIR, '', $file );

					// Detect constructor
					if ( preg_match( '/function\s+__construct\s*\(/i', $contents ) ) {
						$classmap['bootstrap'][] = $key;
					}
				}
			}

			// Save JSON
			$classmap_path = SFTCY_WORDAI_PLUGIN_DIR . 'classmap.json';
			file_put_contents( $classmap_path, json_encode( $classmap, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) );
		}
	}
}
