<?php
/**
 * Runs all active citation queries against configured providers.
 *
 * @package WPLens
 */

namespace WPLens\Citations;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class CitationRunner {

	public function run_active_queries(): array {
		$settings = \WPLens\Utils\Options::all();
		$domain   = (string) ( $settings['citations']['target_domain'] ?? '' );
		if ( '' === $domain ) {
			$host   = wp_parse_url( home_url(), PHP_URL_HOST );
			$domain = $host ?: '';
		}

		$repo    = new CitationRepository();
		$queries = $repo->active_queries();
		$results = array();

		$providers = (array) ( $settings['citations']['providers'] ?? array( 'openai' ) );

		foreach ( $queries as $q ) {
			foreach ( $providers as $prov_slug ) {
				$prov = \WPLens\AI\ProviderRegistry::get( (string) $prov_slug );
				if ( null === $prov || ! $prov->is_configured() || ! $prov->supports_citation_check() ) {
					continue;
				}
				$result = $prov->check_citation( (string) $q['query'], $domain );
				$repo->record_check( (int) $q['id'], $prov->get_slug(), $result );
				$results[] = array(
					'query'    => $q['query'],
					'provider' => $prov->get_slug(),
					'cited'    => $result->cited,
				);
			}
		}

		return $results;
	}

	public function run_single( int $query_id ): array {
		$repo    = new CitationRepository();
		$queries = $repo->all_queries();
		foreach ( $queries as $q ) {
			if ( (int) $q['id'] === $query_id ) {
				$settings = \WPLens\Utils\Options::all();
				$domain   = (string) ( $settings['citations']['target_domain'] ?? wp_parse_url( home_url(), PHP_URL_HOST ) );

				$prov = \WPLens\AI\ProviderRegistry::default();
				if ( null === $prov || ! $prov->is_configured() ) {
					return array( 'ok' => false, 'error' => __( 'Provider not configured.', 'lens-ai-visibility-monitor' ) );
				}

				$result = $prov->check_citation( (string) $q['query'], $domain );
				$repo->record_check( $query_id, $prov->get_slug(), $result );
				return array(
					'ok'       => true,
					'cited'    => $result->cited,
					'position' => $result->position,
					'url'      => $result->cited_url,
				);
			}
		}
		return array( 'ok' => false, 'error' => __( 'Query not found.', 'lens-ai-visibility-monitor' ) );
	}
}
