<?php
/**
 * ============================================================================
 * Class: SftcyWordformClassmapGenerator
 * File:  /includes/class-sftcy-wordform-classmap-generator.php
 * ============================================================================
 * PURPOSE:
 * - Scans all class files under /includes/ matching "class-sftcy-wordform-*.php"
 * - Detects real class declarations (ignoring comments)
 * - Detects which classes contain a __construct() for auto-bootstrap
 * - Builds a case-insensitive JSON map of class => file
 * - Includes plugin metadata (name, version) and generation timestamp
 * - Writes to classmap.json at the plugin root
 *
 * NOTE:
 * ⚠️ This file is automatically regenerated. Do NOT edit classmap.json manually.
 * It will be silently recreated whenever the plugin activates, updates, or
 * if the version in plugin headers changes.
 * ============================================================================
 */

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

if ( ! class_exists( 'SftcyWordformClassmapGenerator' ) ) {

	class SftcyWordformClassmapGenerator {

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

			// 🔍 Read plugin header data to get name/version safely
			$plugin_data = get_file_data(
				SFTCY_WORDFORM_PLUGIN_FILE,
				array(
					'Name'    => 'Plugin Name',
					'Version' => 'Version',
				)
			);

			$plugin_name    = $plugin_data['Name'] ?? 'WordForm Pro';
			$plugin_version = $plugin_data['Version'] ?? SFTCY_WORDFORM_VERSION;

			$classmap = [
				'_comment'       => sprintf(
					'⚠️ AUTO-GENERATED BY %s — DO NOT EDIT MANUALLY. This file will regenerate automatically if deleted, corrupted, or version changes.',
					$plugin_name
				),
				'plugin_name'    => $plugin_name,
				'version'        => $plugin_version,
				'generated_at'   => current_time( 'mysql' ),
				'classes'        => [],
				'bootstrap'      => [], // Classes that have constructors (__construct)
			];

			// 🔍 Scan all includes/class-sftcy-wordform-*.php
			$files = glob( SFTCY_WORDFORM_PLUGIN_INC . 'class-sftcy-wordform-*.php' );

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

				// ❌ Skip backup/temporary files (e.g., .back.php, .backup.php, etc.)
				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;
				}

				// ✅ Match class declaration (ignore commented lines)
				if ( preg_match( '/^[ \t]*class\s+([A-Za-z0-9_]+)/m', $contents, $matches ) ) {
					$class_name = trim( $matches[1] );
					$key        = strtolower( $class_name );

					// 🔑 Save class → file path (relative)
					$classmap['classes'][ $key ] = str_replace( SFTCY_WORDFORM_PLUGIN_DIR, '', $file );

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

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