<?php
if (!defined('ABSPATH')) {
    exit;
}

class VMO_Agent_Orchestrator {
    private static $instance = null;
    private $wpdb;
    private $api_key;
    private $agent_runs_table;
    private $agent_handoffs_table;
    private $website_blueprints_table;
    private $document_recommendations_table;

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

        return self::$instance;
    }

    private function __construct() {
        global $wpdb;

        $this->wpdb = $wpdb;
        $this->api_key = get_option('vmo_openai_api_key', '');
        $this->agent_runs_table = $wpdb->prefix . 'vmo_agent_runs';
        $this->agent_handoffs_table = $wpdb->prefix . 'vmo_agent_handoffs';
        $this->website_blueprints_table = $wpdb->prefix . 'vmo_website_blueprints';
        $this->document_recommendations_table = $wpdb->prefix . 'vmo_document_recommendations';

        add_action('init', array($this, 'ensure_schema'), 6);
    }

    private function prepare_long_running_runtime() {
        if (function_exists('set_time_limit')) {
            @set_time_limit(0);
        }
        if (function_exists('ignore_user_abort')) {
            @ignore_user_abort(true);
        }
        if (function_exists('ini_set')) {
            @ini_set('memory_limit', '512M');
        }
    }

    public function ensure_schema() {
        if (!function_exists('dbDelta')) {
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        }

        $charset_collate = $this->wpdb->get_charset_collate();
        $sql_runs = "CREATE TABLE IF NOT EXISTS {$this->agent_runs_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            session_id VARCHAR(255) NOT NULL,
            agent_key VARCHAR(120) NOT NULL,
            route_task VARCHAR(120) DEFAULT NULL,
            model_used VARCHAR(120) DEFAULT NULL,
            status VARCHAR(40) DEFAULT 'completed',
            input_summary LONGTEXT NULL,
            output_summary LONGTEXT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_user_id (user_id),
            KEY idx_session_id (session_id),
            KEY idx_agent_key (agent_key)
        ) {$charset_collate};";
        $sql_handoffs = "CREATE TABLE IF NOT EXISTS {$this->agent_handoffs_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            session_id VARCHAR(255) NOT NULL,
            from_agent VARCHAR(120) NOT NULL,
            to_agent VARCHAR(120) NOT NULL,
            handoff_summary LONGTEXT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_user_id (user_id),
            KEY idx_session_id (session_id)
        ) {$charset_collate};";
        $sql_blueprints = "CREATE TABLE IF NOT EXISTS {$this->website_blueprints_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            session_id VARCHAR(255) NOT NULL,
            blueprint_json LONGTEXT NULL,
            blueprint_summary LONGTEXT NULL,
            is_active TINYINT(1) DEFAULT 1,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_user_id (user_id),
            KEY idx_session_id (session_id),
            KEY idx_active (is_active)
        ) {$charset_collate};";
        $sql_docs = "CREATE TABLE IF NOT EXISTS {$this->document_recommendations_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            session_id VARCHAR(255) NOT NULL,
            recommendation_json LONGTEXT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_user_id (user_id),
            KEY idx_session_id (session_id)
        ) {$charset_collate};";

        dbDelta($sql_runs);
        dbDelta($sql_handoffs);
        dbDelta($sql_blueprints);
        dbDelta($sql_docs);
    }

    public function sync_consultation_state($user_id, $session_id, array $consultation_state, array $responses = array()) {
        $user_id = (int) $user_id;
        $session_id = (string) $session_id;
        if ($user_id <= 0 || $session_id === '') {
            return array();
        }

        $this->record_handoff($user_id, $session_id, 'conversation_agent', 'jurisdiction_agent', 'Consultation state is being normalized into jurisdiction and brief records.');

        $jurisdiction_profile = function_exists('vmo_get_jurisdiction_engine')
            ? vmo_get_jurisdiction_engine()->resolve_and_save_from_consultation($user_id, $session_id, $consultation_state)
            : array();
        $this->record_agent_run($user_id, $session_id, 'jurisdiction_agent', 'jurisdiction_resolution', array(
            'location' => $consultation_state['extracted_information']['location'] ?? '',
            'business_type' => $consultation_state['extracted_information']['businessType'] ?? ($consultation_state['extracted_information']['business_type'] ?? ''),
        ), $jurisdiction_profile, array(
            'model_used' => function_exists('vmo_get_routed_model') ? vmo_get_routed_model('jurisdiction_resolution', array('skip_log' => true)) : '',
        ));

        $this->record_handoff($user_id, $session_id, 'jurisdiction_agent', 'business_brief_locker_agent', 'Jurisdiction profile is being attached to the canonical master business brief.');
        $brief_bundle = function_exists('vmo_get_master_business_brief_service')
            ? vmo_get_master_business_brief_service()->create_from_consultation($user_id, $session_id, $consultation_state, array(
                'jurisdiction_profile' => $jurisdiction_profile,
                'revision_summary' => 'Master business brief synced from orchestration layer.',
            ))
            : array();
        $this->record_agent_run($user_id, $session_id, 'business_brief_locker_agent', 'business_brief_locking', array(
            'business_name' => $responses['business_name'] ?? ($consultation_state['extracted_information']['businessName'] ?? ''),
            'industry' => $responses['industry'] ?? ($consultation_state['extracted_information']['industry'] ?? ''),
        ), $brief_bundle, array(
            'model_used' => function_exists('vmo_get_routed_model') ? vmo_get_routed_model('business_brief_locking', array('skip_log' => true)) : '',
        ));

        return array(
            'jurisdiction_profile' => $jurisdiction_profile,
            'master_business_brief' => $brief_bundle,
        );
    }

    public function build_execution_package($user_id, $session_id, array $responses, array $research_data = array(), array $existing_package = array(), array $consultation_state = array()) {
        $user_id = (int) $user_id;
        $session_id = (string) $session_id;
        if ($user_id <= 0 || $session_id === '') {
            return array();
        }

        if (empty($consultation_state)) {
            $consultation_state = $this->build_consultation_state_from_responses($responses);
        }

        $state_bundle = $this->sync_consultation_state($user_id, $session_id, $consultation_state, $responses);
        $brief_bundle = $state_bundle['master_business_brief'] ?? array();
        $brief = isset($brief_bundle['brief']) && is_array($brief_bundle['brief']) ? $brief_bundle['brief'] : array();
        $jurisdiction_profile = isset($state_bundle['jurisdiction_profile']) && is_array($state_bundle['jurisdiction_profile'])
            ? $state_bundle['jurisdiction_profile']
            : array();

        $this->record_handoff($user_id, $session_id, 'business_brief_locker_agent', 'document_selection_agent', 'The locked brief now drives document selection and website legal requirements.');
        $document_recommendations = $this->select_documents($brief, $jurisdiction_profile, $responses, $existing_package);
        $this->store_document_recommendations($user_id, $session_id, $document_recommendations);
        $this->record_agent_run($user_id, $session_id, 'document_selection_agent', 'document_need_detection', array(
            'warning_level' => $jurisdiction_profile['legal_warning_level'] ?? 'low',
            'primary_conversion' => $brief['website_goals']['primary_conversion'] ?? '',
        ), $document_recommendations, array(
            'model_used' => 'heuristic',
        ));

        $this->record_handoff($user_id, $session_id, 'document_selection_agent', 'website_architect_agent', 'Document requirements are now embedded into the website blueprint and page map.');
        $website_blueprint = $this->build_website_blueprint($user_id, $session_id, $brief, $research_data, $responses, $document_recommendations, $existing_package);
        $strategic_summary = $this->build_strategic_summary($user_id, $session_id, $brief, $research_data, $existing_package);
        $legal_requirements_text = $this->render_legal_requirements($document_recommendations, $jurisdiction_profile);

        return array(
            'master_business_brief' => $brief_bundle,
            'business_brief_summary' => $brief_bundle['summary'] ?? '',
            'jurisdiction_profile' => $jurisdiction_profile,
            'document_recommendations' => $document_recommendations,
            'website_blueprint' => $website_blueprint,
            'website_architecture' => $website_blueprint['narrative'] ?? ($existing_package['website_architecture'] ?? ''),
            'legal_requirements' => $legal_requirements_text,
            'strategic_agent_summary' => $strategic_summary,
            'website_embedded_docs' => $document_recommendations['website_embedded_docs'] ?? array(),
            'business_overview' => array(
                'business_name' => $brief['business_identity']['business_name'] ?? ($responses['business_name'] ?? ''),
                'industry' => $brief['business_identity']['industry'] ?? ($responses['industry'] ?? ''),
                'target_audience' => $brief['target_audience']['primary_segments'] ?? array(),
                'primary_conversion' => $brief['website_goals']['primary_conversion'] ?? 'lead_capture',
                'jurisdiction' => $jurisdiction_profile['country'] ?? '',
            ),
            'approval_requirements' => array(
                'publish_website',
                'live_legal_injection',
            ),
        );
    }

    public function run_website_qa($user_id, $session_id, $website_payload, array $business_package = array(), array $context = array()) {
        $this->prepare_long_running_runtime();

        $user_id = (int) $user_id;
        $session_id = (string) $session_id;
        if ($user_id <= 0 || $session_id === '' || !function_exists('vmo_get_website_qa_service')) {
            return array();
        }

        $this->record_handoff($user_id, $session_id, 'core_page_builder_agent', 'critic_agent', 'Generated website output is being validated against the locked brief and publish checklist.');
        $report = vmo_get_website_qa_service()->run_qa($user_id, $session_id, $website_payload, $business_package, $context);
        $this->record_agent_run($user_id, $session_id, 'critic_agent', 'website_qa', array(
            'draft_key' => $context['draft_key'] ?? '',
            'related_post_id' => $context['related_post_id'] ?? 0,
        ), $report, array(
            'model_used' => function_exists('vmo_get_routed_model') ? vmo_get_routed_model('website_qa', array('skip_log' => true)) : 'heuristic',
        ));

        return $report;
    }

    /**
     * Public entry point to execute a single website-design agent as a REAL
     * LLM call. Used by VMO_Website_Agent_Runtime to activate the premium
     * ~18-agent website build. Returns the model's text output plus the model
     * used. Fails soft (empty content) when there is no API key or on error,
     * so the canonical pipeline can always fall back to its template path.
     *
     * @return array{content:string,model_used:string,route?:array}
     */
    public function run_design_agent($user_id, $session_id, $agent_key, $prompt, array $context = array()) {
        $this->prepare_long_running_runtime();

        $user_id = (int) $user_id;
        $session_id = (string) $session_id;
        $agent_key = sanitize_key((string) $agent_key);
        $prompt = (string) $prompt;

        if ($agent_key === '' || trim($prompt) === '') {
            return array('content' => '', 'model_used' => 'skipped');
        }
        if (empty($this->api_key)) {
            return array('content' => '', 'model_used' => 'no_api_key');
        }

        $route_task = isset($context['route_task']) ? (string) $context['route_task'] : 'website_design_agent';
        $result = $this->execute_agent_prompt($user_id, $session_id, $agent_key, $route_task, $prompt, $context);

        if ($user_id > 0 && $session_id !== '') {
            $this->record_agent_run($user_id, $session_id, $agent_key, $route_task, array(
                'prompt_chars' => strlen($prompt),
            ), array(
                'summary' => isset($result['content']) ? substr((string) $result['content'], 0, 4000) : '',
            ), array(
                'model_used' => $result['model_used'] ?? '',
            ));
        }

        return $result;
    }

    private function select_documents(array $brief, array $jurisdiction_profile, array $responses, array $existing_package) {
        $must_have = array('privacy_policy', 'terms_of_service');
        $strong = array('business_plan', 'seo_strategy', 'marketing_plan');
        $optional = array('operations_sop', 'proposal_template', 'executive_summary');
        $website_embedded = array('privacy_policy', 'terms_of_service');

        $warning_level = $jurisdiction_profile['legal_warning_level'] ?? 'low';
        $legal_requirements = isset($brief['legal_policy_requirements']) && is_array($brief['legal_policy_requirements'])
            ? $brief['legal_policy_requirements']
            : array();
        $must_have = array_merge($must_have, $legal_requirements);
        $website_embedded = array_merge($website_embedded, $legal_requirements);

        $conversion = $brief['website_goals']['primary_conversion'] ?? 'lead_capture';
        if ($conversion === 'purchase') {
            $must_have[] = 'refund_policy';
            $must_have[] = 'shipping_and_returns';
            $website_embedded[] = 'refund_policy';
        }
        if ($conversion === 'donate') {
            $must_have[] = 'donation_policy';
            $website_embedded[] = 'donation_policy';
        }
        if ($warning_level === 'high') {
            $must_have[] = 'professional_disclaimer';
            $strong[] = 'local_legal_review_note';
        }
        if (!empty($responses['uploaded_documents'])) {
            $strong[] = 'document_ingestion_review';
        }

        return array(
            'must_have_docs' => array_values(array_unique(array_map('sanitize_title', $must_have))),
            'strongly_recommended_docs' => array_values(array_unique(array_map('sanitize_title', $strong))),
            'optional_docs' => array_values(array_unique(array_map('sanitize_title', $optional))),
            'website_embedded_docs' => array_values(array_unique(array_map('sanitize_title', $website_embedded))),
        );
    }

    private function build_website_blueprint($user_id, $session_id, array $brief, array $research_data, array $responses, array $document_recommendations, array $existing_package) {
        $page_map = $this->build_page_map($brief, $responses, $document_recommendations);
        $conversion_flow = $this->build_conversion_flow($brief, $page_map);
        $trust_placement = $this->build_trust_placement($brief, $research_data);
        $media_plan = $this->build_media_plan($brief, $responses, $page_map);
        $stack_tier = $brief['technical_stack_tier'] ?? 'tier_1_professional_standard';

        $blueprint = array(
            'page_map' => $page_map,
            'conversion_flow' => $conversion_flow,
            'trust_placement' => $trust_placement,
            'media_plan' => $media_plan,
            'motion_tier' => $stack_tier === 'tier_2_premium_motion' ? 'premium_motion' : 'professional_standard',
            'stack_tier' => $stack_tier,
            'legal_page_requirements' => $document_recommendations['website_embedded_docs'] ?? array(),
            'narrative' => '',
        );

        $blueprint['narrative'] = $this->render_blueprint_narrative($user_id, $session_id, $blueprint, $brief, $research_data, $existing_package);
        $this->store_website_blueprint($user_id, $session_id, $blueprint);
        $this->record_agent_run($user_id, $session_id, 'website_architect_agent', 'website_architecture', array(
            'page_count' => count($page_map),
            'stack_tier' => $stack_tier,
        ), $blueprint, array(
            'model_used' => function_exists('vmo_get_routed_model') ? vmo_get_routed_model('website_architecture', array('skip_log' => true)) : 'heuristic',
        ));

        return $blueprint;
    }

    private function build_strategic_summary($user_id, $session_id, array $brief, array $research_data, array $existing_package) {
        $fallback = 'Execution package aligned to the locked business brief, jurisdiction profile, market context, and document requirements.';
        $input_summary = array(
            'business_name' => $brief['business_identity']['business_name'] ?? '',
            'industry' => $brief['business_identity']['industry'] ?? '',
            'primary_conversion' => $brief['website_goals']['primary_conversion'] ?? '',
        );

        $prompt = "Create a concise strategic execution summary for this business. Focus on positioning, website purpose, and the immediate implementation priorities.\n\n";
        $prompt .= 'Brief: ' . wp_json_encode(array(
            'business_identity' => $brief['business_identity'] ?? array(),
            'target_audience' => $brief['target_audience'] ?? array(),
            'website_goals' => $brief['website_goals'] ?? array(),
            'growth_goals' => $brief['growth_goals'] ?? array(),
        ));
        if (!empty($research_data)) {
            $prompt .= "\nResearch: " . wp_json_encode($research_data);
        }

        $result = $this->execute_agent_prompt($user_id, $session_id, 'strategic_recommendation_agent', 'strategy_recommendation', $prompt, array(
            'requires_strategic_reasoning' => true,
            'temperature' => 0.2,
            'max_tokens' => 600,
        ));
        $summary = !empty($result['content']) ? $result['content'] : $fallback;

        $this->record_agent_run($user_id, $session_id, 'strategic_recommendation_agent', 'strategy_recommendation', $input_summary, array('summary' => $summary), array(
            'model_used' => $result['model_used'] ?? 'heuristic',
        ));

        return $summary;
    }

    private function execute_agent_prompt($user_id, $session_id, $agent_key, $route_task, $prompt, array $context = array()) {
        $route = function_exists('vmo_get_openai_route')
            ? vmo_get_openai_route($route_task, array(
                'prompt' => $prompt,
                'user_id' => $user_id,
                'requires_strategic_reasoning' => !empty($context['requires_strategic_reasoning']),
                'requires_generation' => !empty($context['requires_generation']),
                'skip_log' => false,
            ))
            : array(
                'model' => defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5',
                'fallback_model' => defined('VMO_OPENAI_FAST_MODEL') ? VMO_OPENAI_FAST_MODEL : null,
            );

        if (empty($this->api_key)) {
            return array(
                'content' => '',
                'model_used' => 'no_api_key',
                'route' => $route,
            );
        }

        $model = $route['model'] ?? (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5');
        $fallback_model = $route['fallback_model'] ?? null;
        $max_tokens = isset($context['max_tokens']) ? (int) $context['max_tokens'] : 800;
        $temperature = isset($context['temperature']) ? (float) $context['temperature'] : 0.2;

        $messages = array(
            array(
                'role' => 'system',
                'content' => 'You are GitHub Copilot operating as the VMO ' . str_replace('_', ' ', $agent_key) . '. Keep output concise, specific, and directly usable inside a business operating system. No markdown code fences.',
            ),
            array(
                'role' => 'user',
                'content' => $prompt,
            ),
        );

        $payload = array_merge(array(
            'model' => $model,
            'messages' => $messages,
            'temperature' => $temperature,
        ), function_exists('vmo_get_token_param') ? vmo_get_token_param($model, $max_tokens) : array('max_tokens' => $max_tokens));

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => wp_json_encode($payload),
            'timeout' => 90,
        ));

        if ((is_wp_error($response) || wp_remote_retrieve_response_code($response) >= 400) && !empty($fallback_model) && $fallback_model !== $model) {
            $payload['model'] = $fallback_model;
            if (isset($payload['max_completion_tokens']) && !preg_match('/^(gpt-5|o1|o3)/i', $fallback_model)) {
                $payload['max_tokens'] = $payload['max_completion_tokens'];
                unset($payload['max_completion_tokens']);
            }
            if (isset($payload['max_tokens']) && preg_match('/^(gpt-5|o1|o3)/i', $fallback_model)) {
                $payload['max_completion_tokens'] = $payload['max_tokens'];
                unset($payload['max_tokens']);
            }
            $response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $this->api_key,
                    'Content-Type' => 'application/json',
                ),
                'body' => wp_json_encode($payload),
                'timeout' => 90,
            ));
            $model = $fallback_model;
        }

        if (is_wp_error($response)) {
            return array(
                'content' => '',
                'model_used' => 'error',
                'route' => $route,
            );
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $content = '';
        if (isset($body['choices'][0]['message']['content'])) {
            $content = trim((string) $body['choices'][0]['message']['content']);
        }

        return array(
            'content' => $content,
            'model_used' => $model,
            'route' => $route,
        );
    }

    private function build_page_map(array $brief, array $responses, array $document_recommendations) {
        $pages = array('home', 'about', 'services', 'contact');
        $custom_pages = isset($brief['website_goals']['desired_pages']) && is_array($brief['website_goals']['desired_pages'])
            ? $brief['website_goals']['desired_pages']
            : array();
        foreach ($custom_pages as $custom_page) {
            $pages[] = sanitize_title((string) $custom_page);
        }

        $conversion = $brief['website_goals']['primary_conversion'] ?? 'lead_capture';
        if ($conversion === 'purchase') {
            $pages[] = 'pricing';
            $pages[] = 'shop';
        }
        if ($conversion === 'donate') {
            $pages[] = 'donate';
        }
        if (!empty($responses['inspiration_websites'])) {
            $pages[] = 'portfolio';
        }

        foreach (($document_recommendations['website_embedded_docs'] ?? array()) as $doc_slug) {
            $pages[] = sanitize_title((string) $doc_slug);
        }

        return array_values(array_unique(array_filter($pages)));
    }

    private function build_conversion_flow(array $brief, array $page_map) {
        $conversion = $brief['website_goals']['primary_conversion'] ?? 'lead_capture';
        $flow = array('home');

        if (in_array('services', $page_map, true)) {
            $flow[] = 'services';
        }
        if ($conversion === 'purchase' && in_array('shop', $page_map, true)) {
            $flow[] = 'shop';
        }
        if ($conversion === 'donate' && in_array('donate', $page_map, true)) {
            $flow[] = 'donate';
        }
        if ($conversion === 'book_appointment') {
            $flow[] = 'contact';
        }
        $flow[] = 'contact';

        return array_values(array_unique($flow));
    }

    private function build_trust_placement(array $brief, array $research_data) {
        $placements = array(
            'home_hero' => array('outcome-focused proof strip', 'primary call to action', 'credibility microcopy'),
            'services' => array('proof blocks near each offer', 'FAQ for objections'),
            'contact' => array('response-time expectation', 'support channels'),
        );

        if (!empty($research_data['competitors'])) {
            $placements['home_social_proof'] = array('competitor-aware differentiation block');
        }

        return $placements;
    }

    private function build_media_plan(array $brief, array $responses, array $page_map) {
        $uploaded_media = isset($responses['uploaded_media']) && is_array($responses['uploaded_media'])
            ? $responses['uploaded_media']
            : array();

        return array(
            'use_uploaded_assets_first' => !empty($uploaded_media),
            'required_slots' => array(
                'home' => array('hero_media', 'trust_graphic'),
                'about' => array('brand_story_media'),
                'services' => array('service_media_grid'),
                'contact' => array('contact_trust_media'),
            ),
            'page_count' => count($page_map),
        );
    }

    private function render_blueprint_narrative($user_id, $session_id, array $blueprint, array $brief, array $research_data, array $existing_package) {
        $narrative = 'Website blueprint: '; 
        $narrative .= 'Page map = ' . implode(', ', $blueprint['page_map']) . '. '; 
        $narrative .= 'Primary conversion = ' . ($brief['website_goals']['primary_conversion'] ?? 'lead_capture') . '. '; 
        $narrative .= 'Stack tier = ' . ($blueprint['stack_tier'] ?? 'tier_1_professional_standard') . '. '; 
        $narrative .= 'Legal pages = ' . implode(', ', $blueprint['legal_page_requirements'] ?? array()) . '. '; 

        $prompt = "Turn this website blueprint into a concise execution narrative for builders. Mention page intent, conversion flow, trust placement, media priorities, and legal injection requirements.\n\n";
        $prompt .= 'Blueprint: ' . wp_json_encode($blueprint) . "\n";
        $prompt .= 'Brief: ' . wp_json_encode(array(
            'business_identity' => $brief['business_identity'] ?? array(),
            'target_audience' => $brief['target_audience'] ?? array(),
            'website_goals' => $brief['website_goals'] ?? array(),
        ));
        if (!empty($research_data)) {
            $prompt .= "\nResearch: " . wp_json_encode($research_data);
        }

        $agent_result = $this->execute_agent_prompt(
            (int) $user_id,
            (string) $session_id,
            'website_architect_agent',
            'website_architecture',
            $prompt,
            array(
                'requires_strategic_reasoning' => true,
                'temperature' => 0.2,
                'max_tokens' => 700,
            )
        );

        if (!empty($agent_result['content'])) {
            return $agent_result['content'];
        }

        return $narrative;
    }

    private function render_legal_requirements(array $document_recommendations, array $jurisdiction_profile) {
        $parts = array();
        $must_have = $document_recommendations['must_have_docs'] ?? array();
        if (!empty($must_have)) {
            $parts[] = 'Required documents: ' . implode(', ', $must_have) . '.';
        }
        if (!empty($jurisdiction_profile['compliance_sensitivity_tags'])) {
            $parts[] = 'Compliance tags: ' . implode(', ', $jurisdiction_profile['compliance_sensitivity_tags']) . '.';
        }
        if (!empty($jurisdiction_profile['legal_warning_level']) && $jurisdiction_profile['legal_warning_level'] === 'high') {
            $parts[] = 'High-risk or regulated content should be reviewed locally before going live.';
        }

        return implode(' ', $parts);
    }

    private function build_consultation_state_from_responses(array $responses) {
        $offers = array();
        if (!empty($responses['strategy']['Core Offerings'])) {
            $offers = preg_split('/[,\n]+/', (string) $responses['strategy']['Core Offerings']);
        }

        $custom_pages = array();
        if (!empty($responses['features_needed'])) {
            $custom_pages = preg_split('/[,\n]+/', (string) $responses['features_needed']);
        }

        $business_goals = (string) ($responses['business_goals'] ?? '');
        $goal_text = strtolower($business_goals);
        $needs_ecommerce = strpos($goal_text, 'e-commerce') !== false || strpos($goal_text, 'ecommerce') !== false || strpos($goal_text, 'shop') !== false || strpos($goal_text, 'store') !== false;
        $needs_donations = strpos($goal_text, 'donation') !== false || strpos($goal_text, 'fundraising') !== false || strpos($goal_text, 'tithe') !== false;

        return array(
            'business_profile' => array(
                'identity' => array(
                    'business_name' => $responses['business_name'] ?? '',
                    'business_type' => $responses['business_type'] ?? '',
                    'industry' => $responses['industry'] ?? '',
                    'hq_location' => $responses['location'] ?? '',
                ),
                'audience' => array(
                    'primary_segments' => !empty($responses['target_audience']) ? array($responses['target_audience']) : array(),
                ),
                'web_requirements' => array(
                    'reference_sites' => $responses['inspiration_websites'] ?? array(),
                    'ecommerce' => $needs_ecommerce,
                    'donations' => $needs_donations,
                ),
            ),
            'extracted_information' => array(
                'businessName' => $responses['business_name'] ?? '',
                'businessType' => $responses['business_type'] ?? '',
                'industry' => $responses['industry'] ?? '',
                'location' => $responses['location'] ?? '',
                'targetAudience' => $responses['target_audience'] ?? '',
                'businessGoals' => $business_goals,
                'websitePreferences' => $responses['style_preferences'] ?? '',
                'colorPreferences' => $responses['color_preferences'] ?? '',
                'offerings' => array_values(array_filter(array_map('trim', is_array($offers) ? $offers : array()))),
                'inspirationWebsites' => $responses['inspiration_websites'] ?? array(),
                'customPages' => array_values(array_filter(array_map('trim', is_array($custom_pages) ? $custom_pages : array()))),
                'needsEcommerce' => $needs_ecommerce,
                'payment_collection_mode' => $needs_donations ? 'donations' : ($needs_ecommerce ? 'products' : 'inquiry'),
            ),
            'consultation_flow' => array(
                'current_phase_index' => 1,
                'status' => 'completed',
            ),
            'approvals' => array(
                'phase1_profile_confirmed' => true,
            ),
            'documents' => $responses['uploaded_documents'] ?? array(),
            'media_files' => $responses['uploaded_media'] ?? array(),
        );
    }

    private function store_website_blueprint($user_id, $session_id, array $blueprint) {
        $this->wpdb->update(
            $this->website_blueprints_table,
            array(
                'is_active' => 0,
                'updated_at' => current_time('mysql'),
            ),
            array(
                'user_id' => (int) $user_id,
                'session_id' => (string) $session_id,
                'is_active' => 1,
            ),
            array('%d', '%s'),
            array('%d', '%s', '%d')
        );

        $this->wpdb->insert(
            $this->website_blueprints_table,
            array(
                'user_id' => (int) $user_id,
                'session_id' => (string) $session_id,
                'blueprint_json' => wp_json_encode($blueprint),
                'blueprint_summary' => $blueprint['narrative'] ?? '',
                'is_active' => 1,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql'),
            ),
            array('%d', '%s', '%s', '%s', '%d', '%s', '%s')
        );
    }

    private function store_document_recommendations($user_id, $session_id, array $recommendations) {
        $this->wpdb->insert(
            $this->document_recommendations_table,
            array(
                'user_id' => (int) $user_id,
                'session_id' => (string) $session_id,
                'recommendation_json' => wp_json_encode($recommendations),
                'created_at' => current_time('mysql'),
            ),
            array('%d', '%s', '%s', '%s')
        );
    }

    private function record_agent_run($user_id, $session_id, $agent_key, $route_task, $input_summary, $output_summary, array $options = array()) {
        $this->wpdb->insert(
            $this->agent_runs_table,
            array(
                'user_id' => (int) $user_id,
                'session_id' => (string) $session_id,
                'agent_key' => (string) $agent_key,
                'route_task' => (string) $route_task,
                'model_used' => (string) ($options['model_used'] ?? ''),
                'status' => (string) ($options['status'] ?? 'completed'),
                'input_summary' => wp_json_encode($input_summary),
                'output_summary' => wp_json_encode($output_summary),
                'created_at' => current_time('mysql'),
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
        );
    }

    private function record_handoff($user_id, $session_id, $from_agent, $to_agent, $summary) {
        $this->wpdb->insert(
            $this->agent_handoffs_table,
            array(
                'user_id' => (int) $user_id,
                'session_id' => (string) $session_id,
                'from_agent' => (string) $from_agent,
                'to_agent' => (string) $to_agent,
                'handoff_summary' => (string) $summary,
                'created_at' => current_time('mysql'),
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s')
        );
    }
}

if (!function_exists('vmo_get_agent_orchestrator')) {
    function vmo_get_agent_orchestrator() {
        return VMO_Agent_Orchestrator::get_instance();
    }
}
