<?php
defined( 'ABSPATH' ) || exit;

class SITECL_AI_Diagnosis {

    private string $api_key;
    private string $model = 'claude-sonnet-4-6';

    public function __construct() {
        $this->api_key = (string) get_option( 'sitecl_claude_api_key', '' );
    }

    /**
     * Diagnose a single PHP error entry.
     *
     * @param  array $error  Keys: type, message, file, line, count.
     * @return array|WP_Error
     */
    public function diagnose_error( array $error ): array|WP_Error {
        if ( empty( $this->api_key ) ) {
            return new WP_Error( 'sitecl_no_key', __( 'Claude API key not configured.', 'site-cliniq' ) );
        }

        $response = wp_remote_post( 'https://api.anthropic.com/v1/messages', [
            'headers' => [
                'x-api-key'         => $this->api_key,
                'anthropic-version' => '2023-06-01',
                'content-type'      => 'application/json',
            ],
            'body'    => wp_json_encode( [
                'model'      => $this->model,
                'max_tokens' => 500,
                'system'     => $this->system_prompt_error(),
                'messages'   => [ [
                    'role'    => 'user',
                    'content' => 'Diagnose this WordPress PHP error and respond ONLY in valid JSON: ' . wp_json_encode( $error ),
                ] ],
            ] ),
            'timeout' => 30,
        ] );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( empty( $body['content'][0]['text'] ) ) {
            return new WP_Error( 'sitecl_bad_response', __( 'Unexpected response from Claude API.', 'site-cliniq' ) );
        }

        $parsed = json_decode( $body['content'][0]['text'], true );

        if ( json_last_error() !== JSON_ERROR_NONE ) {
            return new WP_Error( 'sitecl_json_error', __( 'Claude returned malformed JSON.', 'site-cliniq' ) );
        }

        return $parsed;
    }

    /**
     * Generic diagnosis call — used by CVE checker, bloat detector, etc.
     *
     * @param  string $user_prompt
     * @param  string $system_prompt
     * @param  int    $max_tokens
     * @return array|WP_Error
     */
    public function diagnose( string $user_prompt, string $system_prompt, int $max_tokens = 500 ): array|WP_Error {
        if ( empty( $this->api_key ) ) {
            return new WP_Error( 'sitecl_no_key', __( 'Claude API key not configured.', 'site-cliniq' ) );
        }

        $response = wp_remote_post( 'https://api.anthropic.com/v1/messages', [
            'headers' => [
                'x-api-key'         => $this->api_key,
                'anthropic-version' => '2023-06-01',
                'content-type'      => 'application/json',
            ],
            'body'    => wp_json_encode( [
                'model'      => $this->model,
                'max_tokens' => $max_tokens,
                'system'     => $system_prompt,
                'messages'   => [ [
                    'role'    => 'user',
                    'content' => $user_prompt,
                ] ],
            ] ),
            'timeout' => 30,
        ] );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
        $text   = $body['content'][0]['text'] ?? '';
        $parsed = json_decode( $text, true );

        if ( json_last_error() !== JSON_ERROR_NONE ) {
            return new WP_Error( 'sitecl_json_error', __( 'Claude returned malformed JSON.', 'site-cliniq' ) );
        }

        return $parsed;
    }

    // -------------------------------------------------------------------------
    // System prompts
    // -------------------------------------------------------------------------

    private function system_prompt_error(): string {
        return 'You are a WordPress expert. Diagnose PHP errors in plain English for non-technical site owners.
Always respond ONLY with valid JSON in this exact format:
{
  "plain_english": "What went wrong in one sentence a non-developer understands",
  "cause": "Which plugin, theme, or WP core caused this",
  "severity": "critical|warning|info",
  "fix": "Exact step-by-step fix instruction",
  "safe_to_auto_fix": true|false
}
Never include markdown, explanations, or any text outside the JSON object.';
    }

    public static function system_prompt_cve(): string {
        return 'You are a WordPress security expert. Explain plugin vulnerabilities in plain English for non-technical site owners.
Always respond ONLY with valid JSON in this exact format:
{
  "plain_english": "One sentence explaining the risk to a non-developer",
  "severity": "critical|high|medium|low",
  "action": "Exact step the user should take right now",
  "urgency": "immediate|this-week|monitor"
}
Never include markdown or any text outside the JSON object.';
    }

    public static function system_prompt_update_risk(): string {
        return 'You are a WordPress update expert. Assess plugin update risk based on changelogs and user reports.
Always respond ONLY with valid JSON in this exact format:
{
  "risk_level": "safe|caution|high",
  "plain_english": "One sentence summary of the update risk",
  "breaking_changes": ["list of breaking changes found, empty array if none"],
  "recommendation": "Exact advice: update now, test on staging first, or wait"
}
Never include markdown or any text outside the JSON object.';
    }
}
