<?php

namespace FleekDash\Controllers\Schema;

use FleekDash\Controllers\Schema\FieldProviders\ACFFieldProvider;
use FleekDash\Controllers\Schema\FieldProviders\MetaBoxFieldProvider;
use FleekDash\Controllers\Schema\FieldProviders\VoxelFieldProvider;
use FleekDash\Controllers\Schema\FieldProviders\RESTFieldProvider;
use FleekDash\Controllers\Schema\SchemaHelpers;

/**
 * Schema Extractor
 *
 * Main orchestrator for extracting complete WordPress schema
 * Uses all field providers to build comprehensive schema
 *
 * @package FleekDash\Controllers\Schema
 */
class SchemaExtractor
{
    private $acfProvider;
    private $metaBoxProvider;
    private $voxelProvider;
    private $restProvider;

    public function __construct()
    {
        $this->acfProvider = new ACFFieldProvider();
        $this->metaBoxProvider = new MetaBoxFieldProvider();
        $this->voxelProvider = new VoxelFieldProvider();
        $this->restProvider = new RESTFieldProvider();
    }

    /**
     * Extract full schema for a post type
     *
     * @param string $post_type Post type slug
     * @return array Complete schema
     */
    public function extractFullSchema($post_type)
    {
        return [
            'post_type' => $post_type,
            'post_type_object' => $this->getPostTypeObject($post_type),
            'core_fields' => $this->getCoreFields($post_type),
            'custom_fields' => $this->getCustomFields($post_type),
            'taxonomies' => $this->getTaxonomies($post_type),
            'meta_fields' => $this->getMetaFields($post_type),
            'supports' => $this->getPostTypeSupports($post_type),
            'field_groups' => $this->getFieldGroups($post_type)
        ];
    }

    /**
     * Get post type object details
     *
     * @param string $post_type Post type slug
     * @return array Post type details
     */
    private function getPostTypeObject($post_type)
    {
        $post_type_obj = \call_user_func('get_post_type_object', $post_type);

        return [
            'name' => $post_type_obj->name,
            'label' => $post_type_obj->label,
            'labels' => (array) $post_type_obj->labels,
            'description' => $post_type_obj->description,
            'hierarchical' => $post_type_obj->hierarchical,
            'public' => $post_type_obj->public,
            'show_ui' => $post_type_obj->show_ui,
            'menu_icon' => $post_type_obj->menu_icon,
            'supports' => get_all_post_type_supports($post_type),
            'rest_base' => $post_type_obj->rest_base ?? $post_type
        ];
    }

    /**
     * Get core WordPress fields for post type
     *
     * @param string $post_type Post type slug
     * @return array Core fields
     */
    private function getCoreFields($post_type)
    {
        $supports = get_all_post_type_supports($post_type);
        $core_fields = [];

        // Title field
        if (isset($supports['title'])) {
            $core_fields['title'] = [
                'name' => 'title',
                'label' => 'Title',
                'type' => 'text',
                'required' => true,
                'component' => 'input',
                'validation' => ['required' => true, 'minLength' => 1],
                'description' => 'The title for the post'
            ];
        }

        // Content/Editor field
        if (isset($supports['editor'])) {
            $core_fields['content'] = [
                'name' => 'content',
                'label' => 'Content',
                'type' => 'richtext',
                'required' => false,
                'component' => 'textarea',
                'validation' => [],
                'description' => 'The content for the post'
            ];
        }

        // Excerpt field
        if (isset($supports['excerpt'])) {
            $core_fields['excerpt'] = [
                'name' => 'excerpt',
                'label' => 'Excerpt',
                'type' => 'textarea',
                'required' => false,
                'component' => 'textarea',
                'validation' => [],
                'description' => 'A brief description of the post'
            ];
        }

        // Author field
        if (isset($supports['author'])) {
            $core_fields['author'] = [
                'name' => 'author',
                'label' => 'Author',
                'type' => 'select',
                'required' => false,
                'component' => 'select',
                'options' => SchemaHelpers::getAuthors(),
                'validation' => [],
                'description' => 'The author of the post'
            ];
        }

        // Featured image
        if (isset($supports['thumbnail'])) {
            $core_fields['featured_media'] = [
                'name' => 'featured_media',
                'label' => 'Featured Image',
                'type' => 'media',
                'required' => false,
                'component' => 'file',
                'validation' => [],
                'description' => 'The featured image for the post'
            ];
        }

        // Post status
        $core_fields['status'] = [
            'name' => 'status',
            'label' => 'Status',
            'type' => 'select',
            'required' => true,
            'component' => 'select',
            'options' => SchemaHelpers::getPostStatuses(),
            'default' => 'draft',
            'validation' => ['required' => true],
            'description' => 'The publication status of the post'
        ];

        return $core_fields;
    }

    /**
     * Get custom fields from multiple sources
     *
     * @param string $post_type Post type slug
     * @return array Custom fields
     */
    private function getCustomFields($post_type)
    {
        $custom_fields = [];

        // 1. Get ACF Fields (Priority 10)
        $acf_fields = $this->acfProvider->getACFFields($post_type);
        $custom_fields = array_merge($custom_fields, $acf_fields);

        // 2. Get Meta Box Fields (Priority 9)
        $metabox_fields = $this->metaBoxProvider->getMetaBoxFields($post_type);
        $custom_fields = array_merge($custom_fields, $metabox_fields);

        // 3. Get Voxel Theme Fields (Priority 8)
        $voxel_fields = $this->voxelProvider->getVoxelFields($post_type);
        $custom_fields = array_merge($custom_fields, $voxel_fields);

        // 4. Get WordPress REST API registered meta fields (Priority 7)
        $rest_meta_fields = $this->restProvider->getRESTMetaFields($post_type);
        $custom_fields = array_merge($custom_fields, $rest_meta_fields);

        // 5. Get existing meta keys from database (Priority 1) - LOWEST
        $existing_keys = array_map(function($field) {
            return $field['meta_key'];
        }, $custom_fields);

        $existing_meta_fields = $this->restProvider->getExistingMetaFields($post_type, $existing_keys);
        $custom_fields = array_merge($custom_fields, $existing_meta_fields);

        // Remove duplicates (prioritize higher source priority)
        $unique_fields = [];
        foreach ($custom_fields as $field) {
            $key = $field['name'];
            if (!isset($unique_fields[$key]) || $field['source_priority'] > ($unique_fields[$key]['source_priority'] ?? 0)) {
                $unique_fields[$key] = $field;
            }
        }

        // Load debug helpers
        if (!function_exists('fleekdash_log_debug')) {
            require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
        }
        fleekdash_log_debug("FleekDash: Custom fields summary for {$post_type}:");
        fleekdash_log_debug("- Total fields found: " . count($custom_fields));
        fleekdash_log_debug("- Unique fields after deduplication: " . count($unique_fields));
        fleekdash_log_debug("- Voxel fields: " . count($voxel_fields));

        return $unique_fields;
    }

    /**
     * Get taxonomies for post type
     *
     * @param string $post_type Post type slug
     * @return array Taxonomies
     */
    private function getTaxonomies($post_type)
    {
        $taxonomies = get_object_taxonomies($post_type, 'objects');
        $taxonomy_fields = [];

        foreach ($taxonomies as $taxonomy_slug => $taxonomy) {
            // Include all taxonomies that are visible in admin UI
            if ($taxonomy->show_ui) {
                $terms = \get_terms([
                    'taxonomy' => $taxonomy_slug,
                    'hide_empty' => false,
                    'number' => 100
                ]);

                $term_options = [];
                if (!is_wp_error($terms)) {
                    foreach ($terms as $term) {
                        $term_options[] = [
                            'value' => $term->term_id,
                            'label' => $term->name
                        ];
                    }
                }

                // Determine best component based on taxonomy characteristics
                $term_count = count($term_options);

                if ($term_count <= 5 && !$taxonomy->hierarchical) {
                    $component = 'select';
                    $multiple = false;
                } elseif ($term_count <= 10) {
                    $component = 'multiselect';
                    $multiple = true;
                } else {
                    $component = 'checkbox';
                    $multiple = true;
                }

                $taxonomy_fields[$taxonomy_slug] = [
                    'name' => $taxonomy_slug,
                    'label' => $taxonomy->label,
                    'type' => 'taxonomy',
                    'component' => $component,
                    'required' => false,
                    'multiple' => $multiple,
                    'hierarchical' => $taxonomy->hierarchical,
                    'options' => $term_options,
                    'validation' => [],
                    'description' => $taxonomy->description,
                    'rest_base' => $taxonomy->rest_base ?? $taxonomy_slug
                ];
            }
        }

        return $taxonomy_fields;
    }

    /**
     * Get meta fields
     *
     * @param string $post_type Post type slug
     * @return array Meta fields
     */
    private function getMetaFields($post_type)
    {
        return [];
    }

    /**
     * Get field groups
     *
     * @param string $post_type Post type slug
     * @return array Field groups
     */
    private function getFieldGroups($post_type)
    {
        // Get taxonomies for this post type
        $taxonomies = $this->getTaxonomies($post_type);
        $taxonomy_fields = array_keys($taxonomies);

        // Get custom fields for this post type
        $custom_fields = $this->getCustomFields($post_type);
        $custom_field_names = array_keys($custom_fields);

        $groups = [
            'content' => [
                'label' => 'Content',
                'fields' => ['title', 'content', 'excerpt'],
                'order' => 1
            ],
            'taxonomies' => [
                'label' => 'Categories & Tags',
                'fields' => $taxonomy_fields,
                'order' => 2
            ],
            'custom_fields' => [
                'label' => 'Custom Fields',
                'fields' => $custom_field_names,
                'order' => 3
            ],
            'settings' => [
                'label' => 'Settings',
                'fields' => ['status', 'featured_media'],
                'order' => 4
            ]
        ];

        // Remove empty groups
        foreach ($groups as $key => $group) {
            if (empty($group['fields'])) {
                unset($groups[$key]);
            }
        }

        return $groups;
    }

    /**
     * Get post type supports
     *
     * @param string $post_type Post type slug
     * @return array Supports
     */
    private function getPostTypeSupports($post_type)
    {
        return get_all_post_type_supports($post_type);
    }
}
