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

class VMO_Master_Business_Brief {
    private static $instance = null;
    private $wpdb;
    private $table_name;
    private $revisions_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->table_name = $wpdb->prefix . 'vmo_master_business_briefs';
        $this->revisions_table = $wpdb->prefix . 'vmo_business_brief_revisions';

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

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

        $charset_collate = $this->wpdb->get_charset_collate();
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            session_id VARCHAR(255) NOT NULL,
            brief_version INT UNSIGNED DEFAULT 1,
            brief_hash VARCHAR(64) DEFAULT NULL,
            brief_json LONGTEXT NULL,
            brief_summary LONGTEXT NULL,
            unresolved_assumptions LONGTEXT NULL,
            status VARCHAR(50) DEFAULT 'draft',
            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_revisions = "CREATE TABLE IF NOT EXISTS {$this->revisions_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            brief_id BIGINT UNSIGNED NOT NULL,
            session_id VARCHAR(255) NOT NULL,
            brief_version INT UNSIGNED DEFAULT 1,
            revision_summary LONGTEXT NULL,
            revision_json LONGTEXT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_brief_id (brief_id),
            KEY idx_session_id (session_id)
        ) {$charset_collate};";

        dbDelta($sql);
        dbDelta($sql_revisions);
    }

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

        $brief = $this->build_brief_payload($user_id, $consultation_state, $options);
        $brief_hash = md5(wp_json_encode($brief));
        $summary = $this->build_summary($brief);
        $assumptions = $this->collect_assumptions($brief);
        $status = $this->determine_status($consultation_state);

        $existing = $this->get_active_brief($session_id, $user_id);
        if (!empty($existing['brief_hash']) && $existing['brief_hash'] === $brief_hash) {
            $existing['summary'] = $summary;
            $existing['unresolved_assumptions'] = $assumptions;
            return $existing;
        }

        $version = !empty($existing['brief_version']) ? ((int) $existing['brief_version'] + 1) : 1;

        $this->wpdb->update(
            $this->table_name,
            array(
                'is_active' => 0,
                'updated_at' => current_time('mysql'),
            ),
            array(
                'user_id' => $user_id,
                'session_id' => $session_id,
                'is_active' => 1,
            ),
            array('%d', '%s'),
            array('%d', '%s', '%d')
        );

        $this->wpdb->insert(
            $this->table_name,
            array(
                'user_id' => $user_id,
                'session_id' => $session_id,
                'brief_version' => $version,
                'brief_hash' => $brief_hash,
                'brief_json' => wp_json_encode($brief),
                'brief_summary' => $summary,
                'unresolved_assumptions' => wp_json_encode($assumptions),
                'status' => $status,
                'is_active' => 1,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql'),
            ),
            array('%d', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s')
        );

        $brief_id = (int) $this->wpdb->insert_id;
        $revision_summary = 'Business brief synced from consultation state.';
        if (!empty($options['revision_summary']) && is_string($options['revision_summary'])) {
            $revision_summary = trim($options['revision_summary']);
        }

        $this->wpdb->insert(
            $this->revisions_table,
            array(
                'brief_id' => $brief_id,
                'session_id' => $session_id,
                'brief_version' => $version,
                'revision_summary' => $revision_summary,
                'revision_json' => wp_json_encode(array(
                    'summary' => $summary,
                    'assumptions' => $assumptions,
                    'status' => $status,
                )),
                'created_at' => current_time('mysql'),
            ),
            array('%d', '%s', '%d', '%s', '%s', '%s')
        );

        return array(
            'id' => $brief_id,
            'brief_version' => $version,
            'brief_hash' => $brief_hash,
            'brief' => $brief,
            'summary' => $summary,
            'unresolved_assumptions' => $assumptions,
            'status' => $status,
        );
    }

    public function get_active_brief($session_id, $user_id = 0) {
        $session_id = (string) $session_id;
        if ($session_id === '') {
            return array();
        }

        $sql = "SELECT * FROM {$this->table_name} WHERE session_id = %s AND is_active = 1";
        $params = array($session_id);
        if ((int) $user_id > 0) {
            $sql .= ' AND user_id = %d';
            $params[] = (int) $user_id;
        }
        $sql .= ' ORDER BY id DESC LIMIT 1';

        $row = $this->wpdb->get_row($this->wpdb->prepare($sql, $params), ARRAY_A);
        if (!$row) {
            return array();
        }

        $brief = json_decode($row['brief_json'], true);
        $assumptions = json_decode($row['unresolved_assumptions'], true);

        return array(
            'id' => (int) $row['id'],
            'brief_version' => (int) $row['brief_version'],
            'brief_hash' => (string) ($row['brief_hash'] ?? ''),
            'brief' => is_array($brief) ? $brief : array(),
            'summary' => (string) ($row['brief_summary'] ?? ''),
            'unresolved_assumptions' => is_array($assumptions) ? $assumptions : array(),
            'status' => (string) ($row['status'] ?? 'draft'),
        );
    }

    public function build_compact_summary(array $brief) {
        return $this->build_summary($brief);
    }

    private function build_brief_payload($user_id, array $consultation_state, array $options) {
        $extracted = isset($consultation_state['extracted_information']) && is_array($consultation_state['extracted_information'])
            ? $consultation_state['extracted_information']
            : array();
        $business_profile = isset($consultation_state['business_profile']) && is_array($consultation_state['business_profile'])
            ? $consultation_state['business_profile']
            : array();
        $identity = isset($business_profile['identity']) && is_array($business_profile['identity'])
            ? $business_profile['identity']
            : array();
        $vision = isset($business_profile['vision']) && is_array($business_profile['vision'])
            ? $business_profile['vision']
            : array();
        $targets = isset($business_profile['targets']) && is_array($business_profile['targets'])
            ? $business_profile['targets']
            : array();
        $audience = isset($business_profile['audience']) && is_array($business_profile['audience'])
            ? $business_profile['audience']
            : array();
        $web_requirements = isset($business_profile['web_requirements']) && is_array($business_profile['web_requirements'])
            ? $business_profile['web_requirements']
            : array();
        $documents = isset($consultation_state['documents']) && is_array($consultation_state['documents'])
            ? $consultation_state['documents']
            : array();
        $media_files = isset($consultation_state['media_files']) && is_array($consultation_state['media_files'])
            ? $consultation_state['media_files']
            : array();

        $plan = $options['plan'] ?? get_user_meta($user_id, 'vmo_subscription_status', true);
        $plan_key = function_exists('vmo_normalize_plan_key') ? vmo_normalize_plan_key($plan) : strtolower((string) $plan);
        $scan_config = function_exists('vmo_get_plan_background_ops_config')
            ? vmo_get_plan_background_ops_config($plan_key)
            : array('frequency' => 'none');
        $jurisdiction_profile = isset($options['jurisdiction_profile']) && is_array($options['jurisdiction_profile'])
            ? $options['jurisdiction_profile']
            : array();

        $offers = $this->build_offer_entries($business_profile, $extracted);
        $reference_sites = $this->normalize_list($web_requirements['reference_sites'] ?? ($extracted['inspirationWebsites'] ?? array()));
        $legal_requirements = $this->infer_legal_requirements($jurisdiction_profile, $web_requirements, $extracted);
        $approved_recommendations = $this->normalize_list($consultation_state['approvals']['recommendations']['accepted'] ?? array());
        $approved_documents = $this->normalize_list($options['approved_documents'] ?? array());

        return array(
            'business_identity' => array(
                'business_name' => $this->first_non_empty(array($identity['business_name'] ?? '', $extracted['businessName'] ?? '', $extracted['business_name'] ?? '')),
                'business_type' => $this->first_non_empty(array($identity['business_type'] ?? '', $extracted['businessType'] ?? '', $extracted['business_type'] ?? '')),
                'industry' => $this->first_non_empty(array($identity['industry'] ?? '', $extracted['industry'] ?? '')),
                'location' => $this->first_non_empty(array($identity['hq_location'] ?? '', $extracted['location'] ?? '')),
                'domain' => $this->first_non_empty(array($extracted['domain'] ?? '', $extracted['primaryWebsiteUrl'] ?? '')),
                'business_stage' => $this->first_non_empty(array($extracted['businessStage'] ?? '', 'operating')),
            ),
            'business_model' => array(
                'offering_type' => $this->first_non_empty(array($extracted['offeringType'] ?? '', $identity['business_model'] ?? 'service_business')),
                'revenue_model' => $this->determine_revenue_model($web_requirements, $extracted, $offers),
                'payment_collection_mode' => strtolower((string) ($extracted['payment_collection_mode'] ?? ($extracted['payments_mode'] ?? 'inquiry'))),
                'ecommerce_enabled' => !empty($web_requirements['ecommerce']) || !empty($extracted['needsEcommerce']),
            ),
            'products_services' => $offers,
            'target_audience' => array(
                'primary_segments' => $this->normalize_list($audience['primary_segments'] ?? ($extracted['targetAudience'] ?? '')),
                'pain_points' => $this->normalize_list($audience['pain_points'] ?? array()),
                'motivations' => $this->normalize_list($audience['motivations'] ?? array()),
                'geographies' => $this->normalize_list($audience['geographies'] ?? array()),
            ),
            'offers_pricing' => array(
                'pricing_notes' => $this->first_non_empty(array($extracted['pricing'] ?? '', $extracted['pricingStrategy'] ?? '')),
                'plans' => $this->normalize_list($extracted['pricingTiers'] ?? array()),
                'primary_offer' => !empty($offers[0]['name']) ? $offers[0]['name'] : '',
            ),
            'jurisdiction_profile' => $jurisdiction_profile,
            'website_goals' => array(
                'primary_conversion' => $this->determine_primary_conversion($web_requirements, $extracted),
                'desired_pages' => $this->normalize_list($extracted['customPages'] ?? array()),
                'reference_sites' => $reference_sites,
                'website_status' => $this->first_non_empty(array($extracted['websiteStatus'] ?? '', 'new_build')),
            ),
            'growth_goals' => array(
                'business_goals' => $this->normalize_list($extracted['businessGoals'] ?? ($targets['short_term'] ?? '')),
                'success_definition' => $this->first_non_empty(array($extracted['successDefinition'] ?? '', $extracted['success_definition'] ?? '', $targets['north_star_metric'] ?? '')),
                'north_star_metric' => $this->first_non_empty(array($targets['north_star_metric'] ?? '', $extracted['successDefinition'] ?? '', $extracted['success_definition'] ?? '')),
            ),
            'tone_branding' => array(
                'style_preferences' => $this->normalize_list($extracted['websitePreferences'] ?? ($extracted['website_preferences'] ?? '')),
                'color_preferences' => $this->normalize_list($extracted['colorPreferences'] ?? ($extracted['color_preferences'] ?? '')),
                'brand_values' => $this->normalize_list($vision['core_values'] ?? array()),
            ),
            'deployment_mode' => 'draft_then_approval',
            'technical_stack_tier' => $this->determine_stack_tier($extracted, $web_requirements, $reference_sites),
            'legal_policy_requirements' => $legal_requirements,
            'approved_recommendations' => $approved_recommendations,
            'approved_documents' => $approved_documents,
            'roadmap_assumptions' => array(
                'plan' => $plan_key,
                'scan_frequency' => $scan_config['frequency'] ?? 'none',
                'background_ops_enabled' => !empty($scan_config['enabled']),
            ),
            'kpi_targets' => array(
                'north_star_metric' => $this->first_non_empty(array($targets['north_star_metric'] ?? '', $extracted['successDefinition'] ?? '', 'qualified_leads_and_conversions')),
                'short_term_target' => $this->first_non_empty(array($targets['short_term'] ?? '', 'launch and validate demand')),
                'mid_term_target' => $this->first_non_empty(array($targets['mid_term'] ?? '', 'consistent qualified lead flow')),
                'long_term_target' => $this->first_non_empty(array($targets['long_term'] ?? '', 'durable recurring growth')),
            ),
            'media_style_rules' => array(
                'uploaded_asset_count' => count($media_files),
                'document_count' => count($documents),
                'reference_sites' => $reference_sites,
                'prefer_uploaded_media_first' => true,
            ),
            'voice_preferences' => array(
                'selected_voice' => get_user_meta($user_id, 'vmo_selected_reception_voice', true) ?: 'Ash',
                'cached_first_mode' => true,
            ),
            'scan_frequency' => $scan_config['frequency'] ?? 'none',
            'last_revision_summary' => isset($options['revision_summary']) && is_string($options['revision_summary'])
                ? trim($options['revision_summary'])
                : 'Business brief synchronized from consultation state.',
        );
    }

    private function build_offer_entries(array $business_profile, array $extracted) {
        $offers = array();

        if (!empty($business_profile['offers']) && is_array($business_profile['offers'])) {
            foreach ($business_profile['offers'] as $offer) {
                if (!is_array($offer)) {
                    continue;
                }
                $name = trim((string) ($offer['name'] ?? ''));
                if ($name === '') {
                    continue;
                }
                $offers[] = array(
                    'name' => $name,
                    'description' => trim((string) ($offer['description'] ?? '')),
                    'price' => trim((string) ($offer['price'] ?? '')),
                );
            }
        }

        if (empty($offers)) {
            foreach ($this->normalize_list($extracted['offerings'] ?? array()) as $offering) {
                $offers[] = array(
                    'name' => $offering,
                    'description' => '',
                    'price' => '',
                );
            }
        }

        return $offers;
    }

    private function infer_legal_requirements(array $jurisdiction_profile, array $web_requirements, array $extracted) {
        $requirements = array('privacy_policy', 'terms_of_service');
        $suggestions = isset($jurisdiction_profile['required_policy_suggestions']) && is_array($jurisdiction_profile['required_policy_suggestions'])
            ? $jurisdiction_profile['required_policy_suggestions']
            : array();

        $requirements = array_merge($requirements, $suggestions);
        if (!empty($web_requirements['ecommerce']) || !empty($extracted['needsEcommerce'])) {
            $requirements[] = 'refund_policy';
        }
        if (!empty($web_requirements['donations'])) {
            $requirements[] = 'donation_policy';
        }

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

    private function determine_status(array $consultation_state) {
        $flow = isset($consultation_state['consultation_flow']) && is_array($consultation_state['consultation_flow'])
            ? $consultation_state['consultation_flow']
            : array();
        $current_phase = isset($flow['current_phase_index']) ? (int) $flow['current_phase_index'] : 0;
        $confirmed = !empty($consultation_state['approvals']['phase1_profile_confirmed']);

        if ($confirmed || $current_phase >= 1) {
            return 'locked';
        }

        return 'draft';
    }

    private function determine_primary_conversion(array $web_requirements, array $extracted) {
        if (!empty($web_requirements['ecommerce']) || !empty($extracted['needsEcommerce'])) {
            return 'purchase';
        }
        if (!empty($web_requirements['booking'])) {
            return 'book_appointment';
        }
        if (!empty($web_requirements['donations'])) {
            return 'donate';
        }
        return 'lead_capture';
    }

    private function determine_revenue_model(array $web_requirements, array $extracted, array $offers) {
        if (!empty($web_requirements['donations'])) {
            return 'donations';
        }
        if (!empty($web_requirements['membership'])) {
            return 'membership';
        }
        if (!empty($web_requirements['ecommerce']) || !empty($extracted['needsEcommerce'])) {
            return 'product_sales';
        }
        if (count($offers) > 1) {
            return 'service_packages';
        }

        return 'services';
    }

    private function determine_stack_tier(array $extracted, array $web_requirements, array $reference_sites) {
        if (!empty($reference_sites) || !empty($web_requirements['membership']) || !empty($web_requirements['ecommerce'])) {
            return 'tier_2_premium_motion';
        }
        if (!empty($extracted['websitePreferences']) && stripos((string) $extracted['websitePreferences'], 'immersive') !== false) {
            return 'tier_2_premium_motion';
        }

        return 'tier_1_professional_standard';
    }

    private function build_summary(array $brief) {
        $identity = $brief['business_identity'] ?? array();
        $website_goals = $brief['website_goals'] ?? array();
        $target = $brief['target_audience'] ?? array();
        $growth = $brief['growth_goals'] ?? array();

        $business_name = $identity['business_name'] ?? 'This business';
        $industry = $identity['industry'] ?? 'its industry';
        $audience = !empty($target['primary_segments']) ? implode(', ', array_slice($target['primary_segments'], 0, 3)) : 'its target customers';
        $conversion = $website_goals['primary_conversion'] ?? 'lead_capture';
        $north_star = $growth['north_star_metric'] ?? 'qualified growth';
        $scan_frequency = $brief['scan_frequency'] ?? 'none';

        return sprintf(
            '%s operates in %s, targets %s, and the website is optimized for %s. The current north-star metric is %s, with %s background scan cadence.',
            $business_name,
            $industry,
            $audience,
            $conversion,
            $north_star,
            $scan_frequency
        );
    }

    private function collect_assumptions(array $brief) {
        $assumptions = array();

        if (empty($brief['business_identity']['business_name'])) {
            $assumptions[] = 'Business name still needs explicit confirmation.';
        }
        if (empty($brief['business_identity']['industry'])) {
            $assumptions[] = 'Industry was inferred from context and should be confirmed.';
        }
        if (empty($brief['target_audience']['primary_segments'])) {
            $assumptions[] = 'Target audience segmentation remains light and may need refinement.';
        }
        if (empty($brief['website_goals']['desired_pages'])) {
            $assumptions[] = 'Site map was inferred from the consultation because custom pages were not explicit.';
        }
        if (empty($brief['jurisdiction_profile']['country'])) {
            $assumptions[] = 'Jurisdiction could not be precisely resolved from the available location data.';
        }

        return $assumptions;
    }

    private function normalize_list($value) {
        if (!is_array($value)) {
            if ($value === null || $value === '') {
                return array();
            }
            $value = preg_split('/[,\n]+/', (string) $value);
        }

        return array_values(array_filter(array_map(function ($item) {
            return trim(wp_strip_all_tags((string) $item));
        }, $value)));
    }

    private function first_non_empty(array $values) {
        foreach ($values as $value) {
            if (is_string($value) && trim($value) !== '') {
                return trim($value);
            }
        }

        return '';
    }
}

if (!function_exists('vmo_get_master_business_brief_service')) {
    function vmo_get_master_business_brief_service() {
        return VMO_Master_Business_Brief::get_instance();
    }
}
