<?php

namespace Fotogenic_AI;

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

final class Studio_Page {
    /** Page slug used in admin.php?page=... Must match add_menu_page / add_submenu_page. */
    private const PAGE_SLUG = 'fotogenic-studio';

    private static ?Studio_Page $instance = null;
    private string $page_hook = '';
    private ?array $initial_context = null;

    private function __construct() {}

    public static function instance(): Studio_Page {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function init(): void {
        add_action( 'admin_menu', [ $this, 'register_menu' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
    }

    public function register_menu(): void {
        $this->page_hook = add_menu_page(
            __( 'Fotogenic AI Studio', 'fotogenic-ai' ),
            __( 'Fotogenic AI', 'fotogenic-ai' ),
            fotogenic_ai_minimum_cap(),
            self::PAGE_SLUG,
            [ $this, 'render_page' ],
            'dashicons-camera',
            81
        );
        add_submenu_page(
            self::PAGE_SLUG,
            __( 'Fotogenic AI Studio', 'fotogenic-ai' ),
            __( 'Studio', 'fotogenic-ai' ),
            fotogenic_ai_minimum_cap(),
            self::PAGE_SLUG,
            [ $this, 'render_page' ]
        );
    }

    public function render_page(): void {
        if ( ! fotogenic_ai_user_can_access() ) {
            wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'fotogenic-ai' ) );
        }
		$auth_status      = Auth_Session::instance()->get_public_status();
		$auth_connected   = ! empty( $auth_status['connected'] );
		$studio_context   = $this->resolve_initial_context();
		$studio_targets   = Studio_Targets_Manifest::get_targets();
		$woocommerce_available = Plugin::instance()->compat()->is_woocommerce_active();
		$toolbar_view_model = Studio_Toolbar_View_Model::build(
			$studio_context,
			$studio_targets,
			$woocommerce_available,
			'studio'
		);
		$studio_context   = $this->project_initial_context( $studio_context, $toolbar_view_model['route'] );
		$credits_balance  = array_key_exists( 'balance', $auth_status ) && null !== $auth_status['balance']
            ? (float) $auth_status['balance']
            : null;
        require FOTOGENIC_AI_PATH . 'templates/studio/page.php';
    }

    public function enqueue_assets( string $hook ): void {
        if ( ! fotogenic_ai_user_can_access() ) {
            return;
        }
        if ( empty( $this->page_hook ) || $hook !== $this->page_hook ) {
            return;
        }

        if ( function_exists( 'wp_enqueue_media' ) ) {
            wp_enqueue_media();
        }
        Modules_Registry::instance()->enqueue_shared_assets();
        Studio_Module::instance()->enqueue_core_assets();
		wp_add_inline_style(
			'fotogenic-ai-studio',
			'.fotogenic-ai-studio-page{position:relative}.fotogenic-ai-studio-page[data-fa-ui-state="pending"] [data-fa-studio-application]{visibility:hidden}.fotogenic-ai-studio-page[data-fa-ui-state="ready"] [data-fa-studio-preparing]{display:none}'
		);

		$module_data       = $this->get_studio_module_data();
		$initial_context   = $this->resolve_initial_context();
		$studio_targets    = Studio_Targets_Manifest::get_targets();
		$toolbar_view_model = Studio_Toolbar_View_Model::build(
			$initial_context,
			$studio_targets,
			Plugin::instance()->compat()->is_woocommerce_active(),
			'studio'
		);
		$initial_context   = $this->project_initial_context( $initial_context, $toolbar_view_model['route'] );
		$auth_status      = Auth_Session::instance()->get_public_status();
        $credits_balance  = array_key_exists( 'balance', $auth_status ) && null !== $auth_status['balance']
            ? (float) $auth_status['balance']
            : null;
        wp_add_inline_script(
            'fotogenic-ai-studio-bootstrap',
            fotogenic_ai_build_inline_json_assignment(
                [ 'FotogenicAI', 'Studio', 'boot' ],
                [
                    'nonce'               => wp_create_nonce( 'wp_rest' ),
                    'restUrl'             => rtrim( rest_url( 'fotogenic-ai/v1' ), '/' ),
                    'moduleData'          => $module_data,
                    'workflowManifest'    => Workflow_Registry::get_browser_projection(),
                    'initialContext'      => $initial_context,
                    'creditsBalance'      => $credits_balance,
					'experienceImages'   => Assets_Manifest::studio_experience_images(),
                    'woocommerceAvailable' => Plugin::instance()->compat()->is_woocommerce_active(),
                    'auth'                => $auth_status,
                    'rest'                => [
						'experienceClaim'    => '/experiences/claim',
						'experienceDismiss'  => '/experiences/dismiss',
                        'universalManifest' => '/studio/manifest',
                        'universalPreflight' => '/studio/preflight',
                        'universalStart'    => '/studio/start',
						'activeRun'         => '/studio/run/active',
						'pollRun'           => '/studio/run/poll',
						'globalHistory'     => '/studio/history/runs',
						'resultApply'       => '/studio/results/apply',
                        'resultRemove'      => '/studio/results/remove',
                        'bulkSnapshot'      => '/studio/bulk/snapshot',
                        'bulkStart'         => '/studio/bulk/start',
						'productCategories' => '/studio/product-categories',
						'bulkActive'        => '/studio/bulk/active',
						'bulkProgress'      => '/studio/bulk/progress',
						'bulkPause'         => '/studio/bulk/pause',
						'bulkResume'        => '/studio/bulk/resume',
						'bulkStop'          => '/studio/bulk/stop',
						'storeQueueSnapshot'=> '/studio/store-queue/snapshot',
						'storeQueueProgress'=> '/studio/store-queue/progress',
						'storeQueueStart'   => '/studio/store-queue/start',
						'storeQueueActive'  => '/studio/store-queue/active',
						'storeQueuePause'   => '/studio/store-queue/pause',
						'storeQueueResume'  => '/studio/store-queue/resume',
						'storeQueueStop'    => '/studio/store-queue/stop',
						'configuration'       => '/studio/configuration',
                    ],
                ]
            ),
            'before'
        );

		foreach ( Assets_Manifest::studio_script_handles() as $handle ) {
			wp_set_script_translations( $handle, 'fotogenic-ai', FOTOGENIC_AI_PATH . 'languages' );
		}
    }

	private function get_studio_module_data(): array {
		return [
			'configuration' => $this->get_cached_configuration(),
			'pricing'       => Price_Service::instance()->get_status(),
		];
	}

	private function get_cached_configuration(): ?array {
		$cache_key = Service_Configuration::get_configuration_cache_key();
		$cached = get_transient( $cache_key );
		$configuration_service = new Service_Configuration();
		if ( is_array( $cached ) && isset( $cached['data'] ) && $configuration_service->is_configuration_complete( $cached['data'] ) ) {
			return $configuration_service->present_studio_configuration( $cached['data'] );
		}
		return null;
	}

    private function resolve_initial_context(): array {
        if ( null === $this->initial_context ) {
            $this->initial_context = $this->build_initial_context();
        }

        return $this->initial_context;
    }

    private function build_initial_context(): array {
		$navigation = fotogenic_ai_get_signed_navigation_query_args();
		$route      = [
			'workflow'   => sanitize_key( (string) ( $navigation['workflow'] ?? '' ) ),
			'sourceType' => sanitize_key( (string) ( $navigation['sourceType'] ?? '' ) ),
			'scope'      => sanitize_key( (string) ( $navigation['scope'] ?? '' ) ),
		];
		$source_id  = absint( $navigation['sourceId'] ?? 0 );
		$view       = 'history' === ( $navigation['view'] ?? '' ) ? 'history' : '';
		$source_data = null;

		if ( $source_id > 0 && '' === $view && ! empty( Studio_Toolbar_View_Model::allowlist_route( $route ) ) ) {
			$source_data = $this->get_source_data( $route['sourceType'], $source_id );
		}

		return array_merge(
			$route,
			[
				'sourceId'   => $source_id,
				'sourceData' => $source_data,
				'view'       => $view,
			]
		);
    }

	private function project_initial_context( array $context, array $route ): array {
		$requested_route = [
			'workflow'   => (string) ( $context['workflow'] ?? '' ),
			'sourceType' => (string) ( $context['sourceType'] ?? '' ),
			'scope'      => (string) ( $context['scope'] ?? '' ),
		];
		$source_matches = $requested_route === $route && is_array( $context['sourceData'] ?? null );

		return [
			'workflow'   => (string) ( $route['workflow'] ?? '' ),
			'sourceType' => (string) ( $route['sourceType'] ?? '' ),
			'scope'      => (string) ( $route['scope'] ?? '' ),
			'sourceId'   => $source_matches ? absint( $context['sourceId'] ?? 0 ) : 0,
			'sourceData' => $source_matches ? $context['sourceData'] : null,
			'view'       => 'history' === ( $context['view'] ?? '' ) ? 'history' : '',
		];
	}

	private function get_source_data( string $source_type, int $source_id ): ?array {
		$compat  = Plugin::instance()->compat();
		$adapter = null;
		$data    = null;

		if ( 'product' === $source_type && $compat->is_woocommerce_active() ) {
			$adapter = $compat->get_product_query_adapter();
			$data    = $adapter ? $adapter->get_product_summary( $source_id ) : null;
		} elseif ( 'media' === $source_type ) {
			$adapter = $compat->get_media_query_adapter();
			$data    = $adapter ? $adapter->get_media_summary( $source_id ) : null;
		} elseif ( 'post' === $source_type ) {
			$adapter = $compat->get_post_query_adapter();
			$data    = $adapter ? $adapter->get_post_summary( $source_id ) : null;
		} elseif ( 'page' === $source_type ) {
			$adapter = $compat->get_page_query_adapter();
			$data    = $adapter ? $adapter->get_page_summary( $source_id ) : null;
		}

		if ( ! is_array( $data ) ) {
			return null;
		}

		$data['id'] = $source_id;
		return $data;
	}

}
