<?php

namespace Miruni;

use WP_Theme_JSON_Resolver;
use Exception;

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly


class Miruni_Theme_JSON_Manager
{
    /**
     * Summary of get_theme_json_data
     * @return array<mixed>|null
     */
    public static function get_theme_json_data(): array|null
    {
        return Miruni_Theme_JSON_Manager::read_theme_json_file();
    }

    /**
     * Summary of read_theme_json_file
     * Reads the theme.json file directly from the theme directory.
     * 
     * @return array<mixed>|null Returns the decoded JSON data or null if the file does not exist.
     */
    public static function read_theme_json_file(): array|null
    {
        $theme_json_path = get_template_directory() . '/theme.json';
        error_log("Miruni_Theme_JSON_Manager: Reading theme.json from $theme_json_path");

        if (file_exists($theme_json_path)) {
            $json_content = file_get_contents($theme_json_path);
            if ($json_content === false) {
                error_log('Error reading theme.json file: ' . $theme_json_path);
                return null;
            }
            $decoded = json_decode($json_content, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                if (is_array($decoded)) {
                    return $decoded;
                }
            } else {
                error_log('Error decoding theme.json: ' . json_last_error_msg());
            }
        }

        return null;
    }

    /**
     * Apply theme.json changes from draft meta
     * 
     * @param int $draft_id ID of the draft post containing changes
     * @return array{success: bool, message: string, updated_data?: array<mixed>}
     */
    public static function apply_theme_json_changes(int $draft_id): array
    {
        try {
            $theme_json_changes = get_post_meta($draft_id, Miruni_Preview_Meta_Keys::THEME_JSON, true);

            if (!is_array($theme_json_changes) || empty($theme_json_changes)) {
                return [
                    'success' => true,
                    'message' => 'No theme.json changes to apply'
                ];
            }

            // Get the stored theme.json data
            if (!isset($theme_json_changes['theme_json']) || !is_array($theme_json_changes['theme_json'])) {
                return [
                    'success' => false,
                    'message' => 'Invalid theme.json data in draft'
                ];
            }

            $updated_theme_json = $theme_json_changes['theme_json'];

            // Write the updated theme.json to file
            $success = self::write_theme_json_file($updated_theme_json);

            if ($success) {
                // Clear any relevant caches
                // if (function_exists('wp_clean_themes_cache')) {
                //     wp_clean_themes_cache();
                // }

                // // Clear WP_Theme_JSON_Resolver cache if available
                // if (class_exists('WP_Theme_JSON_Resolver')) {
                //     // Force reload of theme data on next request
                //     wp_cache_delete('theme_json', 'themes');
                // }

                return [
                    'success' => true,
                    'message' => 'Theme.json changes applied successfully',
                    'updated_data' => $updated_theme_json
                ];
            } else {
                return [
                    'success' => false,
                    'message' => 'Failed to write theme.json file'
                ];
            }
        } catch (Exception $e) {
            error_log('Error applying theme.json changes: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Exception while applying theme.json changes: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Write theme.json data to the theme file
     * 
     * @param array<mixed> $theme_json_data The theme.json data to write
     * @return bool True on success, false on failure
     */
    public static function write_theme_json_file(array $theme_json_data): bool
    {
        $theme_json_path = get_template_directory() . '/theme.json';

        // Create backup of original file if it exists
        if (file_exists($theme_json_path)) {
            $backup_path = $theme_json_path . '.miruni-backup-' . time();
            if (!copy($theme_json_path, $backup_path)) {
                error_log('Failed to create backup of theme.json: ' . $theme_json_path);
                return false;
            }
        }

        // Convert array to JSON with pretty printing
        $json_content = json_encode($theme_json_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        if ($json_content === false) {
            error_log('Failed to encode theme.json data to JSON');
            return false;
        }

        // Write to file
        $result = file_put_contents($theme_json_path, $json_content);

        if ($result === false) {
            error_log('Failed to write theme.json file: ' . $theme_json_path);
            return false;
        }

        return true;
    }

    /**
     * Create a backup of current theme.json data for reversion
     * 
     * @return array<mixed>|null Current theme.json data or null if not available
     */
    public static function create_theme_json_backup(): array|null
    {
        return self::get_theme_json_data();
    }

    /**
     * Restore theme.json from backup data
     * 
     * @param array<mixed> $backup_data The backup data to restore
     * @return bool True on success, false on failure
     */
    public static function restore_theme_json_from_backup(array $backup_data): bool
    {
        return self::write_theme_json_file($backup_data);
    }

}