<?php

namespace FleekDash\API;

// Load debug helpers
if (!function_exists('fleekdash_log_error')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use FleekDash\Core\AuthMiddleware;

/**
 * Theme Directory API
 *
 * Provides advanced theme directory browsing, search, and installation
 * with WordPress.org API integration and async installation support.
 *
 * @package FleekDash\API
 */
class ThemeDirectoryAPI
{
    /**
     * Cache duration for WordPress.org API responses
     */
    const CACHE_SEARCH_DURATION = 3600; // 1 hour
    const CACHE_DETAILS_DURATION = 21600; // 6 hours
    const CACHE_TAGS_DURATION = 86400; // 24 hours

    /**
     * Constructor
     *
     * Migrated (v2.2): PluginsRoutes (Phase 2)
     * add_action removed - routes now registered via ThemeDirectoryController
     */
    public function __construct()
    {
    }

    /**
     * Register REST API routes
     */
    public function register_routes() // NOSONAR php:S100 — method name matches register_rest_route callback string
    {
        $namespace = 'fleekdash/v1';

        // Search & Browse
        \register_rest_route($namespace, '/theme-directory/search', array(
            'methods' => 'GET',
            'callback' => array($this, 'search_themes'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => $this->get_search_args()
        ));

        \register_rest_route($namespace, '/theme-directory/theme/(?P<slug>[a-zA-Z0-9_-]+)', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_theme_details'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        \register_rest_route($namespace, '/theme-directory/tags', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_tags'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        \register_rest_route($namespace, '/theme-directory/featured', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_featured'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        // Installation
        \register_rest_route($namespace, '/theme-directory/install', array(
            'methods' => 'POST',
            'callback' => array($this, 'install_theme'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => array(
                'slug' => array('required' => true, 'type' => 'string'),
                'activate' => array('required' => false, 'type' => 'boolean', 'default' => false),
            ),
        ));

        \register_rest_route($namespace, '/theme-directory/install-status/(?P<job_id>[a-zA-Z0-9_-]+)', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_install_status'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        \register_rest_route($namespace, '/theme-directory/cancel-install/(?P<job_id>[a-zA-Z0-9_-]+)', array(
            'methods' => 'DELETE',
            'callback' => array($this, 'cancel_install'),
            'permission_callback' => array($this, 'check_permissions'),
        ));
    }

    /**
     * Get search arguments schema
     */
    private function get_search_args() // NOSONAR php:S100 — WordPress REST helper naming convention
    {
        return array(
            'query' => array(
                'type' => 'string',
                'required' => false,
                'default' => '',
            ),
            'page' => array(
                'type' => 'integer',
                'required' => false,
                'default' => 1,
                'minimum' => 1,
            ),
            'per_page' => array(
                'type' => 'integer',
                'required' => false,
                'default' => 20,
                'minimum' => 1,
                'maximum' => 100,
            ),
            'browse' => array(
                'type' => 'string',
                'required' => false,
                'enum' => array('popular', 'featured', 'new', 'updated'),
            ),
            'tag' => array(
                'type' => 'string',
                'required' => false,
            ),
            'author' => array(
                'type' => 'string',
                'required' => false,
            ),
        );
    }

    /**
     * Check permissions
     */
    public function check_permissions() // NOSONAR php:S100 — matches permission_callback in register_rest_route
    {
        return true; // Let AuthMiddleware handle auth
    }

    /**
     * Search themes from WordPress.org
     */
    public function search_themes(WP_REST_Request $request) // NOSONAR php:S100,php:S3776,php:S1142 — WP REST callback name; structured flow
    {
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
                fleekdash_log_debug('FleekDash: Theme directory access without auth: ' . $auth_check['reason']);
            }

            $query = $request->get_param('query');
            $page = $request->get_param('page');
            $per_page = $request->get_param('per_page');
            $browse = $request->get_param('browse');
            $tag = $request->get_param('tag');
            $author = $request->get_param('author');

            // Build cache key
            $cache_key = 'fleekdash_theme_search_' . md5(serialize($request->get_params()));
            $cached = \get_transient($cache_key);

            if ($cached !== false) {
                return \rest_ensure_response($cached);
            }

            // Prepare WordPress.org API arguments
            $api_args = array(
                'page' => $page,
                'per_page' => $per_page,
                'fields' => array(
                    'description' => true,
                    'sections' => false,
                    'rating' => true,
                    'ratings' => true,
                    'downloaded' => true,
                    'downloadlink' => true,
                    'last_updated' => true,
                    'homepage' => true,
                    'tags' => true,
                    'screenshot_url' => true,
                    'active_installs' => true,
                ),
            );

            // Add search query
            if (!empty($query)) {
                $api_args['search'] = $query;
            }

            // Add browse mode
            if (!empty($browse)) {
                $api_args['browse'] = $browse;
            }

            // Add tag
            if (!empty($tag)) {
                $api_args['tag'] = $tag;
            }

            // Add author
            if (!empty($author)) {
                $api_args['author'] = $author;
            }

            // Query WordPress.org Themes API
            $url = 'https://api.wordpress.org/themes/info/1.2/?' . http_build_query(array(
                'action' => 'query_themes',
                'request' => $api_args,
            ));

            $response = \wp_remote_get($url, array('timeout' => 15));

            if (is_wp_error($response)) {
                return new WP_Error(
                    'api_error',
                    'WordPress.org Themes API error: ' . $response->get_error_message(),
                    array('status' => 500)
                );
            }

            $body = wp_remote_retrieve_body($response);
            $api_response = json_decode($body);

            if (!$api_response || !isset($api_response->themes)) {
                return new WP_Error('api_error', 'Invalid API response', array('status' => 500));
            }

            // Get installed themes for comparison
            $installed_themes = wp_get_themes();
            $current_theme = wp_get_theme();

            // Format results
            $results = array();
            if (!empty($api_response->themes)) {
                foreach ($api_response->themes as $theme) {
                    $formatted = ThemeDirectoryFormatter::format($theme, $installed_themes, $current_theme);
                    if ($formatted !== null) {
                        $results[] = $formatted;
                    }
                }
            }

            // Build response
            $response_data = array(
                'success' => true,
                'results' => $results,
                'pagination' => array(
                    'page' => $page,
                    'per_page' => $per_page,
                    'total' => isset($api_response->info->results) ? $api_response->info->results : 0,
                    'total_pages' => isset($api_response->info->pages) ? $api_response->info->pages : 0,
                ),
                'filters_applied' => array(
                    'query' => $query,
                    'browse' => $browse,
                    'tag' => $tag,
                    'author' => $author,
                ),
            );

            // Cache the response
            \set_transient($cache_key, $response_data, self::CACHE_SEARCH_DURATION);

            return \rest_ensure_response($response_data);

        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Theme directory search error: ' . $e->getMessage());
            return new WP_Error('search_error', 'Error searching themes', array('status' => 500));
        }
    }

    /**
     * Get theme details
     */
    public function get_theme_details(WP_REST_Request $request) // NOSONAR php:S100,php:S1142 — WP REST callback; multiple response paths
    {
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
                fleekdash_log_debug('FleekDash: Theme details access without auth');
            }

            $slug = $request->get_param('slug');

            // Check cache
            $cache_key = 'fleekdash_theme_details_' . $slug;
            $cached = \get_transient($cache_key);

            if ($cached !== false) {
                return \rest_ensure_response($cached);
            }

            // Query WordPress.org Themes API
            $url = "https://api.wordpress.org/themes/info/1.2/?action=theme_information&request[slug]={$slug}&request[fields][description]=true&request[fields][sections]=true&request[fields][rating]=true&request[fields][ratings]=true&request[fields][downloaded]=true&request[fields][screenshot_url]=true&request[fields][screenshots]=true&request[fields][tags]=true&request[fields][versions]=true";

            $response = \wp_remote_get($url, array('timeout' => 15));

            if (is_wp_error($response)) {
                return new WP_Error('api_error', 'Theme not found or API error', array('status' => 404));
            }

            $body = wp_remote_retrieve_body($response);
            $api_response = json_decode($body);

            if (!$api_response) {
                return new WP_Error('api_error', 'Theme not found', array('status' => 404));
            }

            // Get installed themes for comparison
            $installed_themes = wp_get_themes();
            $current_theme = wp_get_theme();

            // Format theme data
            $formatted = ThemeDirectoryFormatter::format($api_response, $installed_themes, $current_theme, true);

            // Cache the response
            \set_transient($cache_key, array('success' => true, 'theme' => $formatted), self::CACHE_DETAILS_DURATION);

            return \rest_ensure_response(array(
                'success' => true,
                'theme' => $formatted,
            ));

        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Theme details error: ' . $e->getMessage());
            return new WP_Error('details_error', 'Error getting theme details', array('status' => 500));
        }
    }

    /**
     * Get popular tags
     */
    public function get_tags(WP_REST_Request $request) // NOSONAR php:S100 — WP REST callback name
    {
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
                fleekdash_log_debug('FleekDash: Theme tags access without auth');
            }

            // Check cache
            $cache_key = 'fleekdash_theme_tags';
            $cached = \get_transient($cache_key);

            if ($cached !== false) {
                return \rest_ensure_response($cached);
            }

            // Popular theme tags
            $tags = array(
                array('slug' => 'blog', 'name' => 'Blog', 'count' => 0),
                array('slug' => 'e-commerce', 'name' => 'E-Commerce', 'count' => 0),
                array('slug' => 'portfolio', 'name' => 'Portfolio', 'count' => 0),
                array('slug' => 'photography', 'name' => 'Photography', 'count' => 0),
                array('slug' => 'business', 'name' => 'Business', 'count' => 0),
                array('slug' => 'one-column', 'name' => 'One Column', 'count' => 0),
                array('slug' => 'two-columns', 'name' => 'Two Columns', 'count' => 0),
                array('slug' => 'three-columns', 'name' => 'Three Columns', 'count' => 0),
                array('slug' => 'full-width-template', 'name' => 'Full Width', 'count' => 0),
                array('slug' => 'responsive', 'name' => 'Responsive', 'count' => 0),
                array('slug' => 'custom-menu', 'name' => 'Custom Menu', 'count' => 0),
                array('slug' => 'featured-images', 'name' => 'Featured Images', 'count' => 0),
            );

            $response_data = array(
                'success' => true,
                'tags' => $tags,
            );
            $response_data = \apply_filters('fleekdash_theme_directory_tags', $response_data, $request);

            // Cache for 24 hours
            \set_transient($cache_key, $response_data, self::CACHE_TAGS_DURATION);

            return \rest_ensure_response($response_data);

        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Theme tags error: ' . $e->getMessage());
            return new WP_Error('tags_error', 'Error getting tags', array('status' => 500));
        }
    }

    /**
     * Get featured themes
     */
    public function get_featured(WP_REST_Request $request) // NOSONAR php:S100 — WP REST callback name
    {
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
                fleekdash_log_debug('FleekDash: Featured themes access without auth');
            }

            // Use search with browse=featured
            $request->set_param('browse', 'featured');
            $request->set_param('per_page', 24);
            return $this->search_themes($request);

        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Featured themes error: ' . $e->getMessage());
            return new WP_Error('featured_error', 'Error getting featured themes', array('status' => 500));
        }
    }

    /**
     * Install theme (synchronous in this request — same model as plugin-directory/install).
     */
    public function install_theme(WP_REST_Request $request) // NOSONAR php:S100 — WP REST callback name
    {
        try {
            $auth_check = AuthMiddleware::check('admin');
            if (!$auth_check['authenticated']) {
                return new WP_Error('unauthorized', 'Admin access required', array('status' => 403));
            }

            $slug = $request->get_param('slug');
            $activate = $request->get_param('activate');

            if (!\is_string($slug) || $slug === '') {
                return new WP_Error('invalid_slug', 'Theme slug is required', array('status' => 400));
            }

            if (\function_exists('set_time_limit')) {
                @\set_time_limit(600);
            }
            if (\function_exists('ignore_user_abort')) {
                @\ignore_user_abort(true);
            }

            $job_id = 'install_theme_' . $slug . '_' . time();

            $job_status = array(
                'state' => 'downloading',
                'progress' => 0,
                'step' => 'Starting installation for ' . $slug,
                'started_at' => \current_time('mysql'),
                'logs' => array(
                    '[' . \current_time('mysql') . '] Starting theme installation for ' . $slug,
                ),
                'slug' => $slug,
                'activate' => $activate,
            );

            \set_transient('fleekdash_install_theme_job_' . $job_id, $job_status, 3600);

            ThemeDirectoryInstaller::processInstallation($job_id);

            $final = \get_transient('fleekdash_install_theme_job_' . $job_id);
            if ($final === false) {
                return new WP_Error('install_lost', 'Installation finished but job status was not found', array('status' => 500));
            }

            $is_complete = isset($final['state']) && $final['state'] === 'complete';
            $message = $is_complete
                ? ($final['step'] ?? 'Theme installed successfully')
                : ($final['error'] ?? $final['step'] ?? 'Installation failed');

            return \rest_ensure_response(array(
                'success' => $is_complete,
                'job_id' => $job_id,
                'message' => $message,
                'status' => $final,
            ));

        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Install theme error: ' . $e->getMessage());
            return new WP_Error('install_error', 'Error starting installation: ' . $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Get installation status
     */
    public function get_install_status(WP_REST_Request $request) // NOSONAR php:S100 — WP REST callback name
    {
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
                fleekdash_log_debug('FleekDash: Theme install status without auth');
            }

            $job_id = $request->get_param('job_id');

            $job_status = \get_transient('fleekdash_install_theme_job_' . $job_id);

            if ($job_status === false) {
                return new WP_Error('job_not_found', 'Installation job not found', array('status' => 404));
            }

            return \rest_ensure_response(array(
                'success' => true,
                'job_id' => $job_id,
                'status' => $job_status,
            ));

        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Theme install status error: ' . $e->getMessage());
            return new WP_Error('status_error', 'Error getting status', array('status' => 500));
        }
    }

    /**
     * Cancel installation
     */
    public function cancel_install(WP_REST_Request $request) // NOSONAR php:S100 — WP REST callback name
    {
        try {
            $auth_check = AuthMiddleware::check('admin');
            if (!$auth_check['authenticated']) {
                return new WP_Error('unauthorized', 'Admin access required', array('status' => 403));
            }

            $job_id = $request->get_param('job_id');

            // Delete the job transient
            \delete_transient('fleekdash_install_theme_job_' . $job_id);

            return \rest_ensure_response(array(
                'success' => true,
                'message' => 'Theme installation cancelled',
            ));

        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Cancel theme install error: ' . $e->getMessage());
            return new WP_Error('cancel_error', 'Error cancelling installation', array('status' => 500));
        }
    }

}
