<?php

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

final class Aysa_AI_Visibility_API_Client {
    public function request($path, $payload = array()) {
        $path = '/' . ltrim((string) $path, '/');
        if (strpos($path, '/v1/ai-visibility/') !== 0) {
            return new WP_Error('aysa_ai_visibility_path_invalid', __('Invalid AI Visibility API path.', 'aysaaiseo'));
        }

        $access_key = $this->access_key();
        if ($access_key === '') {
            return new WP_Error('aysa_ai_visibility_access_key_missing', __('Connect AYSA before using AI Visibility.', 'aysaaiseo'));
        }

        $host = strtolower((string) wp_parse_url(home_url('/'), PHP_URL_HOST));
        $host = preg_replace('/^www\./', '', trim($host));
        $payload = is_array($payload) ? $payload : array();
        $payload['site_host'] = $host;
        $project_id = absint(get_option('aysa_project_id', 0));
        $website_id = absint(get_option('aysa_website_id', 0));
        if ($project_id > 0) {
            $payload['project_id'] = $project_id;
        }
        if ($website_id > 0) {
            $payload['website_id'] = $website_id;
        }

        $body = wp_json_encode($payload);
        if (!is_string($body)) {
            return new WP_Error('aysa_ai_visibility_json_failed', __('Could not encode the AI Visibility request.', 'aysaaiseo'));
        }
        $headers = $this->signed_headers($path, $body);
        if (is_wp_error($headers)) {
            return $headers;
        }
        $headers['Authorization'] = 'Bearer ' . $access_key;

        $base_url = defined('AYSA_API_BASE_URL')
            ? (string) AYSA_API_BASE_URL
            : (class_exists('Aysa_API_Config') ? (string) Aysa_API_Config::get_base_url() : 'https://api.aysa.ai/');
        $response = wp_remote_post(rtrim($base_url, '/') . $path, array(
            'timeout' => 30,
            'redirection' => 0,
            'headers' => $headers,
            'body' => $body,
        ));
        if (is_wp_error($response)) {
            return $response;
        }

        $status = (int) wp_remote_retrieve_response_code($response);
        $decoded = json_decode((string) wp_remote_retrieve_body($response), true);
        if (!is_array($decoded)) {
            return new WP_Error('aysa_ai_visibility_invalid_response', __('AI Visibility returned an invalid response.', 'aysaaiseo'));
        }
        if ($status < 200 || $status >= 300 || empty($decoded['ok'])) {
            $error_code = sanitize_key((string) ($decoded['error'] ?? 'aysa_ai_visibility_request_failed'));
            return new WP_Error(
                $error_code,
                sanitize_text_field($error_code),
                array('status' => $status)
            );
        }
        return $decoded;
    }

    private function access_key() {
        $access_key = trim((string) get_option('aysa_active_access_key', ''));
        if ($access_key === '') {
            $access_key = trim((string) get_option('aysa_user_secret_key', ''));
        }
        if ($access_key !== '') {
            return $access_key;
        }

        if (!class_exists('Aysa_Auth_Manager')) {
            $auth_file = AYSA_PLUGIN_DIR . 'includes/class-aysa-auth-manager.php';
            if (is_readable($auth_file)) {
                require_once $auth_file;
            }
        }
        if (!class_exists('Aysa_Auth_Manager')) {
            return '';
        }

        $auth = Aysa_Auth_Manager::get_instance()->is_authenticated();
        if (empty($auth['authenticated'])) {
            return '';
        }
        return trim((string) ($auth['secret_key'] ?? ''));
    }

    private function signed_headers($path, $body) {
        $key_id = defined('AYSA_OAUTH_BROKER_KEY_ID')
            ? trim((string) AYSA_OAUTH_BROKER_KEY_ID)
            : trim((string) get_option('aysa_oauth_broker_key_id', 'wp_plugin'));
        $secret = defined('AYSA_OAUTH_BROKER_KEY_SECRET')
            ? trim((string) AYSA_OAUTH_BROKER_KEY_SECRET)
            : trim((string) get_option('aysa_oauth_broker_key_secret', ''));
        if ($key_id === '' || $secret === '') {
            return new WP_Error(
                'aysa_ai_visibility_hmac_missing',
                __('The secure AYSA connection is not configured.', 'aysaaiseo')
            );
        }
        $timestamp = (string) time();
        try {
            $nonce = bin2hex(random_bytes(16));
        } catch (Throwable $error) {
            $nonce = wp_generate_password(32, false, false);
        }
        $canonical = implode("\n", array(
            'POST',
            $path,
            hash('sha256', (string) $body),
            $timestamp,
            $nonce,
        ));
        return array(
            'Content-Type' => 'application/json',
            'X-Aysa-Key' => $key_id,
            'X-Aysa-Timestamp' => $timestamp,
            'X-Aysa-Nonce' => $nonce,
            'X-Aysa-Signature' => hash_hmac('sha256', $canonical, $secret),
        );
    }
}
