<?php

if (!defined('WPINC')) {
    die;
}

class Aysa_Confidence_Scorer {
    
    private $thresholds;
    
    public function __construct() {
        $this->thresholds = array(
            'auto_approve' => get_option('aysa_auto_approve_threshold', 0.9),
            'suggest' => get_option('aysa_suggest_threshold', 0.7),
            'manual_review' => get_option('aysa_manual_review_threshold', 0.5)
        );
    }
    
    public function calculate_image_confidence($image_data, $generated_content) {
        $confidence = 0.0;
        $factors = array();
        
        $confidence += $this->score_image_quality($image_data);
        $factors['image_quality'] = $this->score_image_quality($image_data);
        
        $confidence += $this->score_content_relevance($image_data, $generated_content);
        $factors['content_relevance'] = $this->score_content_relevance($image_data, $generated_content);
        
        $confidence += $this->score_context_match($image_data, $generated_content);
        $factors['context_match'] = $this->score_context_match($image_data, $generated_content);
        
        $confidence += $this->score_api_confidence($generated_content);
        $factors['api_confidence'] = $this->score_api_confidence($generated_content);
        
        $final_confidence = min($confidence / 4, 1.0);
        
        return array(
            'score' => $final_confidence,
            'factors' => $factors,
            'recommendation' => $this->get_recommendation($final_confidence),
            'threshold_met' => $this->get_threshold_status($final_confidence)
        );
    }
    
    public function calculate_redirect_confidence($error_data, $suggested_url) {
        $confidence = 0.0;
        $factors = array();
        
        $confidence += $this->score_url_similarity($error_data['url'], $suggested_url);
        $factors['url_similarity'] = $this->score_url_similarity($error_data['url'], $suggested_url);
        
        $confidence += $this->score_hit_frequency($error_data['hit_count']);
        $factors['hit_frequency'] = $this->score_hit_frequency($error_data['hit_count']);
        
        $confidence += $this->score_user_agent_quality($error_data);
        $factors['user_agent_quality'] = $this->score_user_agent_quality($error_data);
        
        $confidence += $this->score_target_validity($suggested_url);
        $factors['target_validity'] = $this->score_target_validity($suggested_url);
        
        $final_confidence = min($confidence / 4, 1.0);
        
        return array(
            'score' => $final_confidence,
            'factors' => $factors,
            'recommendation' => $this->get_recommendation($final_confidence),
            'threshold_met' => $this->get_threshold_status($final_confidence)
        );
    }
    
    public function calculate_meta_confidence($content_data, $generated_meta) {
        $confidence = 0.0;
        $factors = array();
        
        $confidence += $this->score_keyword_integration($content_data, $generated_meta);
        $factors['keyword_integration'] = $this->score_keyword_integration($content_data, $generated_meta);
        
        $confidence += $this->score_length_optimization($generated_meta);
        $factors['length_optimization'] = $this->score_length_optimization($generated_meta);
        
        $confidence += $this->score_content_relevance_meta($content_data, $generated_meta);
        $factors['content_relevance'] = $this->score_content_relevance_meta($content_data, $generated_meta);
        
        $confidence += $this->score_uniqueness($generated_meta);
        $factors['uniqueness'] = $this->score_uniqueness($generated_meta);
        
        $final_confidence = min($confidence / 4, 1.0);
        
        return array(
            'score' => $final_confidence,
            'factors' => $factors,
            'recommendation' => $this->get_recommendation($final_confidence),
            'threshold_met' => $this->get_threshold_status($final_confidence)
        );
    }
    
    public function calculate_domain_authority_confidence($task_data) {
        $confidence = 0.0;
        $factors = array();
        
        $confidence += $this->score_domain_authority_metrics($task_data);
        $factors['domain_authority_metrics'] = $this->score_domain_authority_metrics($task_data);
        
        $confidence += $this->score_backlink_quality($task_data);
        $factors['backlink_quality'] = $this->score_backlink_quality($task_data);
        
        $confidence += $this->score_competitor_analysis($task_data);
        $factors['competitor_analysis'] = $this->score_competitor_analysis($task_data);
        
        $confidence += $this->score_task_feasibility($task_data);
        $factors['task_feasibility'] = $this->score_task_feasibility($task_data);
        
        $final_confidence = min($confidence / 4, 1.0);
        
        return array(
            'score' => $final_confidence,
            'factors' => $factors,
            'recommendation' => $this->get_recommendation($final_confidence),
            'threshold_met' => $this->get_threshold_status($final_confidence)
        );
    }
    
    public function calculate_association_confidence($task_data) {
        $factors = array();
        $score = 0.0;
        
        // Association count factor (higher count = higher confidence)
        $association_count = $task_data['association_count'] ?? 0;
        if ($association_count > 0) {
            $count_score = min(1.0, $association_count / 50); // Normalize to 50 associations
            $factors['association_count'] = $count_score;
            $score += $count_score * 0.4;
        }
        
        $feasibility_score = 0.8; // Association tasks are generally feasible
        $factors['task_feasibility'] = $feasibility_score;
        $score += $feasibility_score * 0.3;
        
        $activity_score = 0.7; // Default activity score
        $factors['project_activity'] = $activity_score;
        $score += $activity_score * 0.3;
        
        $final_confidence = round($score, 2);
        $recommendation = $final_confidence >= 0.7 ? 'approve' : 'review';
        
        return array(
            'score' => $final_confidence,
            'factors' => $factors,
            'recommendation' => $recommendation,
            'threshold_met' => $this->get_threshold_status($final_confidence),
            'explanation' => "Association task confidence based on {$association_count} keywords to associate"
        );
    }
    
    private function score_domain_authority_metrics($task_data) {
        $score = 0.0;
        
        if (isset($task_data['target_authority']) && $task_data['target_authority'] > 0) {
            if ($task_data['target_authority'] >= 50) $score += 0.3;
            else if ($task_data['target_authority'] >= 30) $score += 0.2;
            else $score += 0.1;
        }
        
        if (isset($task_data['target_backlinks']) && $task_data['target_backlinks'] > 0) {
            if ($task_data['target_backlinks'] <= 20) $score += 0.2;
            else if ($task_data['target_backlinks'] <= 50) $score += 0.15;
            else $score += 0.1;
        }
        
        return min($score, 0.5);
    }
    
    private function score_backlink_quality($task_data) {
        $score = 0.2;
        
        if (isset($task_data['competitor_data']) && is_array($task_data['competitor_data'])) {
            $competitor_count = count($task_data['competitor_data']);
            if ($competitor_count >= 3) $score += 0.2;
            else if ($competitor_count >= 2) $score += 0.1;
        }
        
        return min($score, 0.4);
    }
    
    private function score_competitor_analysis($task_data) {
        $score = 0.0;
        
        if (isset($task_data['competitor_data']) && is_array($task_data['competitor_data'])) {
            foreach ($task_data['competitor_data'] as $competitor) {
                if (isset($competitor['averageDomainAuthority']) && $competitor['averageDomainAuthority'] > 0) {
                    $score += 0.05;
                }
                if (isset($competitor['backlinksCount']) && $competitor['backlinksCount'] > 0) {
                    $score += 0.05;
                }
            }
        }
        
        return min($score, 0.3);
    }
    
    private function score_task_feasibility($task_data) {
        $score = 0.2;
        
        if (isset($task_data['title']) && !empty($task_data['title'])) {
            $score += 0.1;
        }
        
        if (isset($task_data['description']) && !empty($task_data['description'])) {
            $score += 0.1;
        }
        
        return min($score, 0.4);
    }
    
    private function score_image_quality($image_data) {
        $score = 0.0;
        
        if (isset($image_data['width']) && isset($image_data['height'])) {
            $pixels = $image_data['width'] * $image_data['height'];
            if ($pixels > 500000) $score += 0.3;
            else if ($pixels > 100000) $score += 0.2;
            else $score += 0.1;
        }
        
        if (isset($image_data['file_size'])) {
            if ($image_data['file_size'] > 50000 && $image_data['file_size'] < 2000000) {
                $score += 0.2;
            }
        }
        
        return min($score, 0.5);
    }
    
    private function score_content_relevance($image_data, $generated_content) {
        $score = 0.0;
        
        if (!empty($generated_content['alt_text'])) {
            $alt_length = strlen($generated_content['alt_text']);
            if ($alt_length > 10 && $alt_length < 125) {
                $score += 0.3;
            }
        }
        
        if (!empty($generated_content['description'])) {
            $desc_length = strlen($generated_content['description']);
            if ($desc_length > 20 && $desc_length < 300) {
                $score += 0.2;
            }
        }
        
        return min($score, 0.5);
    }
    
    private function score_context_match($image_data, $generated_content) {
        $score = 0.0;
        
        if (isset($image_data['context'])) {
            $context_keywords = $this->extract_keywords($image_data['context']);
            $content_text = implode(' ', $generated_content);
            
            foreach ($context_keywords as $keyword) {
                if (stripos($content_text, $keyword) !== false) {
                    $score += 0.1;
                }
            }
        }
        
        return min($score, 0.5);
    }
    
    private function score_api_confidence($generated_content) {
        if (isset($generated_content['api_confidence'])) {
            return $generated_content['api_confidence'] * 0.5;
        }
        
        return 0.25;
    }
    
    private function score_url_similarity($source_url, $target_url) {
        $source_parts = parse_url($source_url);
        $target_parts = parse_url($target_url);
        
        $score = 0.0;
        
        if (isset($source_parts['path']) && isset($target_parts['path'])) {
            $similarity = 0;
            similar_text($source_parts['path'], $target_parts['path'], $similarity);
            $score += ($similarity / 100) * 0.4;
        }
        
        $source_segments = explode('/', trim($source_parts['path'] ?? '', '/'));
        $target_segments = explode('/', trim($target_parts['path'] ?? '', '/'));
        
        $common_segments = array_intersect($source_segments, $target_segments);
        if (count($common_segments) > 0) {
            $score += 0.3;
        }
        
        return min($score, 0.7);
    }
    
    private function score_hit_frequency($hit_count) {
        if ($hit_count >= 10) return 0.3;
        if ($hit_count >= 5) return 0.2;
        if ($hit_count >= 2) return 0.1;
        return 0.05;
    }
    
    private function score_user_agent_quality($error_data) {
        if (isset($error_data['is_bot']) && $error_data['is_bot']) {
            return 0.1;
        }
        
        return 0.3;
    }
    
    private function score_target_validity($target_url) {
        $response = wp_remote_head($target_url);
        
        if (!is_wp_error($response)) {
            $status_code = wp_remote_retrieve_response_code($response);
            if ($status_code === 200) {
                return 0.4;
            }
        }
        
        return 0.1;
    }
    
    private function score_keyword_integration($content_data, $generated_meta) {
        $score = 0.0;
        
        if (!empty($content_data['primary_keyword'])) {
            $keyword = strtolower($content_data['primary_keyword']);
            
            if (stripos($generated_meta['title'] ?? '', $keyword) !== false) {
                $score += 0.2;
            }
            
            if (stripos($generated_meta['description'] ?? '', $keyword) !== false) {
                $score += 0.2;
            }
        }
        
        return min($score, 0.4);
    }
    
    private function score_length_optimization($generated_meta) {
        $score = 0.0;
        
        if (isset($generated_meta['title'])) {
            $title_length = strlen($generated_meta['title']);
            if ($title_length >= 30 && $title_length <= 60) {
                $score += 0.2;
            }
        }
        
        if (isset($generated_meta['description'])) {
            $desc_length = strlen($generated_meta['description']);
            if ($desc_length >= 120 && $desc_length <= 160) {
                $score += 0.2;
            }
        }
        
        return min($score, 0.4);
    }
    
    private function score_content_relevance_meta($content_data, $generated_meta) {
        $score = 0.0;
        
        if (!empty($content_data['content'])) {
            $content_keywords = $this->extract_keywords($content_data['content']);
            $meta_text = implode(' ', $generated_meta);
            
            foreach ($content_keywords as $keyword) {
                if (stripos($meta_text, $keyword) !== false) {
                    $score += 0.05;
                }
            }
        }
        
        return min($score, 0.3);
    }
    
    private function score_uniqueness($generated_meta) {
        global $wpdb;
        
        $score = 0.3;
        
        if (isset($generated_meta['title'])) {
            $existing = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = '_yoast_wpseo_title' AND meta_value = %s",
                $generated_meta['title']
            ));
            
            if ($existing > 0) {
                $score -= 0.1;
            }
        }
        
        return max($score, 0.1);
    }
    
    private function extract_keywords($text) {
        $words = str_word_count(strtolower($text), 1);
        $words = array_filter($words, function($word) {
            return strlen($word) > 3;
        });
        
        return array_slice(array_unique($words), 0, 10);
    }
    
    private function get_recommendation($confidence) {
        if ($confidence >= $this->thresholds['auto_approve']) {
            return 'auto_approve';
        } else if ($confidence >= $this->thresholds['suggest']) {
            return 'suggest';
        } else if ($confidence >= $this->thresholds['manual_review']) {
            return 'manual_review';
        } else {
            return 'reject';
        }
    }
    
    private function get_threshold_status($confidence) {
        return array(
            'auto_approve' => $confidence >= $this->thresholds['auto_approve'],
            'suggest' => $confidence >= $this->thresholds['suggest'],
            'manual_review' => $confidence >= $this->thresholds['manual_review']
        );
    }
    
    public function update_thresholds($new_thresholds) {
        foreach ($new_thresholds as $key => $value) {
            if (isset($this->thresholds[$key])) {
                $this->thresholds[$key] = floatval($value);
                update_option('aysa_' . $key . '_threshold', $value);
            }
        }
    }
    
    public function get_thresholds() {
        return $this->thresholds;
    }
}
