<?php
/**
 * Metadata-only catalog of Pro modules for the Lite hub.
 *
 * wordpress.org Lite must not ship Pro PHP. This file lists names and
 * descriptions so the Modules hub can show "Requires WP PowerSuite Pro".
 *
 * @package WP_PowerSuite\Core
 * @since 1.1.0
 */

namespace WP_PowerSuite\Core;

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

/**
 * Read-only Pro module catalog.
 */
final class ProModuleCatalog {

	/**
	 * @return array<string, array<string, mixed>>
	 */
	public static function getEntries(): array {
		$path = defined( 'WP_POWERSUITE_PLUGIN_DIR' )
			? WP_POWERSUITE_PLUGIN_DIR . 'data' . DIRECTORY_SEPARATOR . 'pro-modules-catalog.json'
			: '';

		if ( $path === '' || ! is_readable( $path ) ) {
			return [];
		}

		$raw = file_get_contents( $path );
		if ( ! is_string( $raw ) || $raw === '' ) {
			return [];
		}

		$payload = json_decode( $raw, true );
		if ( ! is_array( $payload ) || empty( $payload['modules'] ) || ! is_array( $payload['modules'] ) ) {
			return [];
		}

		$entries = [];
		foreach ( $payload['modules'] as $module_id => $meta ) {
			if ( ! is_array( $meta ) ) {
				continue;
			}

			$id = sanitize_key( (string) ( $meta['id'] ?? $module_id ) );
			if ( $id === '' ) {
				continue;
			}

			$entries[ $id ] = [
				'id'          => $id,
				'name'        => sanitize_text_field( (string) ( $meta['name'] ?? $id ) ),
				'description' => sanitize_textarea_field( (string) ( $meta['description'] ?? '' ) ),
				'category'    => sanitize_text_field( (string) ( $meta['category'] ?? 'uncategorized' ) ),
				'tags'        => self::sanitize_tags( $meta['tags'] ?? [] ),
				'version'     => sanitize_text_field( (string) ( $meta['version'] ?? '1.0.0' ) ),
				'is_pro'      => true,
				'is_freemium' => false,
				'_directory'  => '',
			];
		}

		return $entries;
	}

	/**
	 * Add catalog rows for Pro modules that are not installed on disk.
	 *
	 * @param array<string, array<string, mixed>> $installed Registry modules.
	 * @return array<string, array<string, mixed>>
	 */
	public static function mergeForHub( array $installed ): array {
		if ( ! function_exists( 'wp_powersuite_is_lite_edition' ) || ! wp_powersuite_is_lite_edition() ) {
			return $installed;
		}

		if ( function_exists( 'wp_powersuite_is_pro_addon_active' ) && wp_powersuite_is_pro_addon_active() ) {
			return $installed;
		}

		foreach ( self::getEntries() as $id => $meta ) {
			if ( ! isset( $installed[ $id ] ) ) {
				$installed[ $id ] = $meta;
			}
		}

		return $installed;
	}

	/**
	 * @param mixed $tags Raw tags.
	 * @return list<string>
	 */
	private static function sanitize_tags( mixed $tags ): array {
		if ( ! is_array( $tags ) ) {
			return [];
		}

		$out = [];
		foreach ( $tags as $tag ) {
			if ( ! is_string( $tag ) && ! is_int( $tag ) ) {
				continue;
			}
			$key = sanitize_key( (string) $tag );
			if ( $key !== '' ) {
				$out[] = $key;
			}
		}

		return $out;
	}
}
