<?php

namespace AIPT\Api\Chatbot\Diag;

use AIPT\Api\Chatbot\ChatbotLogger;
use AIPT\Utils\Credentials\CredentialResolver;

class DiagController {

	private const PROVIDERS = [ 'openai', 'gemini', 'claude', 'openrouter' ];
	private const SELF_PROBE_TIMEOUT = 10;

	public function register_routes(): void {
		register_rest_route(
			'aipt/v1',
			'/diag',
			[
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => [ $this, 'get_diag' ],
				'permission_callback' => [ $this, 'check_permissions' ],
			]
		);

		register_rest_route(
			'aipt/v1/chatbot',
			'/test-payload',
			[
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => [ $this, 'get_test_payload' ],
				'permission_callback' => static function (): bool {
					return true;
				},
			]
		);
	}

	public function check_permissions( \WP_REST_Request $request ) {
		unset( $request );

		return \current_user_can( 'manage_options' );
	}

	public function get_diag( \WP_REST_Request $request ): \WP_REST_Response {
		unset( $request );

		return new \WP_REST_Response(
			[
				'provider_ping'  => $this->getProviderPing(),
				'self_probe'     => $this->getSelfProbe(),
				'timeout_config' => $this->getTimeoutConfig(),
				'last_error'     => ChatbotLogger::getLastError(),
			],
			200
		);
	}

	public function get_test_payload( \WP_REST_Request $request ): \WP_REST_Response {
		unset( $request );

		return new \WP_REST_Response(
			[
				'ok'      => true,
				'payload' => 'union select 1,2,3 -- AIPT_SELF_PROBE_BENIGN',
			],
			200
		);
	}

	private function getProviderPing(): array {
		$auth_status = \get_transient( 'aipt_chatbot_provider_auth_status' );
		$auth_status = is_array( $auth_status ) ? $auth_status : [];
		$ping        = [];

		foreach ( self::PROVIDERS as $provider ) {
			$ping[ $provider ] = [
				'configured'      => $this->isProviderConfigured( $provider ),
				'last_auth_error' => ( $auth_status['provider'] ?? '' ) === $provider ? $auth_status : null,
			];
		}

		return $ping;
	}

	private function isProviderConfigured( string $provider ): bool {
		try {
			return CredentialResolver::instance()->isConfigured( $provider );
		} catch ( \Throwable $e ) {
			unset( $e );
			return false;
		}
	}

	private function getSelfProbe(): array {
		$response = \call_user_func(
			'wp_remote_get',
			\call_user_func( 'rest_url', 'aipt/v1/chatbot/test-payload' ),
			[
				'user-agent' => 'aipt-self-probe',
				'timeout'    => self::SELF_PROBE_TIMEOUT,
			]
		);

		if ( \call_user_func( 'is_wp_error', $response ) ) {
			return [
				'reachable'            => false,
				'status_code'          => 0,
				'waf_block_suspected'  => false,
			];
		}

		$status_code = (int) \call_user_func( 'wp_remote_retrieve_response_code', $response );

		return [
			'reachable'           => 200 === $status_code,
			'status_code'         => $status_code,
			'waf_block_suspected' => 200 !== $status_code,
		];
	}

	private function getTimeoutConfig(): array {
		return [
			'self_probe_timeout_seconds' => self::SELF_PROBE_TIMEOUT,
		];
	}
}
