<?php
namespace EncypherProvenance;

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

require_once __DIR__ . '/class-encypher-logger.php';

class WordPress_AI_Compat
{
    private const OPTION_KEY = 'encypher_provenance_settings';

    public function register_hooks(): void
    {
        add_action('plugins_loaded', [$this, 'maybe_hook_into_wordpress_ai'], 20);
    }

    public function maybe_hook_into_wordpress_ai(): void
    {
        if (!$this->is_wordpress_ai_active()) {
            return;
        }

        $settings = get_option(self::OPTION_KEY, []);
        $enabled = !empty($settings['wordpress_ai_enabled']);
        if (!$enabled) {
            return;
        }

        add_filter('wp_ai_experiment_title_generation_result', [$this, 'sign_ai_content'], 10, 2);
        add_filter('wp_ai_experiment_excerpt_generation_result', [$this, 'sign_ai_content'], 10, 2);
        add_filter('wp_ai_experiment_summary_generation_result', [$this, 'sign_ai_content'], 10, 2);
        add_filter('wp_ai_experiment_review_notes_result', [$this, 'sign_ai_content'], 10, 2);
        add_filter('wp_ai_experiment_alt_text_result', [$this, 'sign_ai_content'], 10, 2);

        add_action('wp_abilities_api_init', [$this, 'on_abilities_api_init']);
    }

    public function is_wordpress_ai_active(): bool
    {
        if (function_exists('is_plugin_active') && is_plugin_active('wordpress-ai/plugin.php')) {
            return true;
        }
        if (class_exists('WP_AI\\Plugin') || class_exists('WordPressAI\\Plugin') || class_exists('WP_AI_Experiments\\Plugin')) {
            return true;
        }
        if (function_exists('wp_abilities_api_init') || function_exists('wp_register_ability') || function_exists('wp_do_ability')) {
            return true;
        }
        return false;
    }

    public function sign_ai_content(string $content, array $context = []): string
    {
        if (empty(trim($content))) {
            return $content;
        }

        $settings = get_option(self::OPTION_KEY, []);
        $api_base = rtrim($settings['api_base_url'] ?? 'https://api.encypher.com/api/v1', '/');
        $api_key  = $settings['api_key'] ?? '';

        if (empty($api_key)) {
            return $content;
        }

        $post_id = isset($context['post_id']) ? (int) $context['post_id'] : 0;
        $install_id = trim((string) ($settings['install_id'] ?? ''));
        if ($post_id <= 0 || '' === $install_id) {
            $this->debug_log('sign_ai_content refused: durable WordPress post/install identity is unavailable');
            return $content;
        }

        $experiment = $this->get_current_filter_name();
        $request_fingerprint = hash('sha256', wp_json_encode([
            'content' => $content,
            'post_id' => $post_id,
            'experiment' => $experiment,
            'generator' => $context['model'] ?? $context['provider'] ?? 'wordpress/ai',
        ]));
        $pending_meta_key = '_encypher_wpai_operation_pending_' . substr(hash('sha256', $experiment), 0, 16);
        $pending = get_post_meta($post_id, $pending_meta_key, true);
        if (
            is_array($pending)
            && hash_equals($request_fingerprint, (string) ($pending['request_fingerprint'] ?? ''))
            && '' !== (string) ($pending['generation'] ?? '')
        ) {
            $generation = (string) $pending['generation'];
        } else {
            $generation = wp_generate_uuid4();
            $pending = [
                'request_fingerprint' => $request_fingerprint,
                'generation' => $generation,
            ];
            $persisted = update_post_meta($post_id, $pending_meta_key, $pending);
            if (false === $persisted && get_post_meta($post_id, $pending_meta_key, true) !== $pending) {
                $this->debug_log('sign_ai_content refused: operation identity could not be persisted');
                return $content;
            }
        }

        try {
            $inventory_contract = SignRequestBuilder::build_wordpress_inventory_contract(
                $settings,
                $post_id,
                $generation,
                [
                    'generator' => $context['model'] ?? $context['provider'] ?? 'wordpress/ai',
                    'experiment' => $experiment,
                ]
            );
        } catch (\InvalidArgumentException $error) {
            $this->debug_log('sign_ai_content refused: ' . $error->getMessage());
            return $content;
        }


        $sign_context = [
            'document_id' => $inventory_contract['document_id'],
            'work_id' => $inventory_contract['logical_asset_id'],
            'is_ai_content' => true,
            'claim_generator' => 'WordPress/ai + Encypher Plugin v' . (defined('ENCYPHER_PROVENANCE_VERSION') ? ENCYPHER_PROVENANCE_VERSION : '0.0.0'),
            'metadata' => $inventory_contract['metadata'],
        ];

        $payload = SignRequestBuilder::build_text_sign_payload($content, $sign_context, $settings);

        $response = ApiUrlGuard::guarded_remote_post(
            $api_base . '/sign',
            [
                'headers' => [
                    'Authorization' => 'Bearer ' . $api_key,
                    'Content-Type'  => 'application/json',
                    'Idempotency-Key' => $inventory_contract['operation_key'],
                ],
                'body'    => wp_json_encode($payload),
                'timeout' => 20, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- authenticated AI-ability sign call (Abilities API); not a front-end request.
            ]
        );

        if (is_wp_error($response)) {
            $this->debug_log('sign_ai_content error: ' . $response->get_error_message());
            return $content;
        }

        $status = wp_remote_retrieve_response_code($response);
        if ($status < 200 || $status >= 300) {
            $this->debug_log('sign_ai_content non-200 status: ' . $status);
            return $content;
        }

        $data = json_decode(wp_remote_retrieve_body($response), true);
        $signed_text = $data['data']['document']['signed_text']
            ?? $data['data']['signed_text']
            ?? $data['signed_text']
            ?? null;

        if (!is_string($signed_text) || empty($signed_text)) {
            $this->debug_log('sign_ai_content: no signed_text in response');
            return $content;
        }

        delete_post_meta($post_id, $pending_meta_key);
        $this->record_signed_experiment($post_id, $sign_context['metadata']);

        return $signed_text;
    }

    private function record_signed_experiment(int $post_id, array $metadata): void
    {
        $existing = get_post_meta($post_id, '_encypher_wpai_experiments', true);
        if (!is_array($existing)) {
            $existing = [];
        }

        $experiment_name = $metadata['experiment'] ?? 'unknown';

        $existing[$experiment_name] = [
            'name'       => $experiment_name,
            'generator'  => $metadata['generator'] ?? null,
            'signed_at'  => $metadata['generated_at'] ?? gmdate('c'),
        ];

        update_post_meta($post_id, '_encypher_wpai_experiments', $existing);
    }

    public function on_abilities_api_init(): void
    {
        do_action('encypher_abilities_api_ready');
    }

    private function get_current_filter_name(): string
    {
        return current_filter() ?: 'unknown';
    }

    private function debug_log(string $message): void
    {
        Logger::log('Encypher WordPress/ai: ' . $message);
    }
}
