<?php
/**
 * PoC: Semantic Deduplication
 * Run with: wp eval-file tests/poc_semantic_deduplication.php
 */

// Load WordPress environment if not loaded
if ( ! defined( 'ABSPATH' ) ) {
	require_once __DIR__ . '/../wisewand-plugin.php';
}

use Wisewand\Utils\OpenAI_Client;
use Wisewand\Utils\Semantic_Deduplication_Engine;
use Wisewand\Repositories\Keyword_Repository;
use Wisewand\Logging\Logger;

$logger = new Logger();
$repo   = new Keyword_Repository();
$api_key = OpenAI_Client::get_stored_api_key();

if ( empty( $api_key ) ) {
	die( "❌ No OpenAI API Key found in settings.\n" );
}

$client = new OpenAI_Client( $api_key, $logger );
$engine = new Semantic_Deduplication_Engine( $logger, $client, $repo );

echo "🚀 Starting Semantic Deduplication PoC...\n";

// Test Pairs
$pairs = [
	['Best running shoes', 'Top running sneakers'], // Should be high match
	['How to bake a cake', 'Cake baking guide'],    // Should be high match
	['Apple iPhone 15', 'Samsung Galaxy S24'],      // Should be low/medium match (both phones)
	['Best running shoes', 'Banana bread recipe'],  // Should be near zero
];

foreach ( $pairs as $pair ) {
	echo "\nComparing: '{$pair[0]}' vs '{$pair[1]}'\n";
	
	$vec1 = $client->get_embeddings( $pair[0] );
	$vec2 = $client->get_embeddings( $pair[1] );

	if ( is_wp_error( $vec1 ) || is_wp_error( $vec2 ) ) {
		echo "❌ Error generating embeddings.\n";
		continue;
	}

	// Calculate similarity manually for PoC
	$score = calculate_cosine_similarity( $vec1, $vec2 );
	echo "📊 Similarity Score: " . number_format( $score, 4 ) . "\n";
	
	if ( $score > 0.9 ) echo "✅ DUPLICATE DETECTED\n";
	elseif ( $score > 0.8 ) echo "⚠️  HIGHLY RELATED\n";
	else echo "🆗 UNIQUE\n";
}

function calculate_cosine_similarity( $vec_a, $vec_b ) {
	$dot_product = 0;
	$norm_a      = 0;
	$norm_b      = 0;

	foreach ( $vec_a as $key => $val ) {
		$dot_product += $val * $vec_b[ $key ];
		$norm_a      += $val * $val;
		$norm_b      += $vec_b[ $key ] * $vec_b[ $key ];
	}

	return $dot_product / ( sqrt( $norm_a ) * sqrt( $norm_b ) );
}
