<?php

class SAVEAMSU_AI_Client {

    public static function summarize_post( $post ) {
        $settings = SAVEAMSU_Settings::get_settings();
        $api_key  = $settings['api_key'];

        if ( empty( $api_key ) ) {
            return ''; // No summary if no key
        }

        $content = wp_strip_all_tags( $post->post_content );
        $content = mb_substr( $content, 0, 4000 ); // safety limit

        $prompt = "Summarize the following blog post in 2–3 short bullet points, in plain English, highlighting the main ideas:\n\n" . $content;

        $body = array(
            'model' => 'gpt-4o-mini',
            'messages' => array(
                array(
                    'role' => 'user',
                    'content' => $prompt,
                ),
            ),
            'max_tokens' => 200,
        );

        $response = wp_remote_post(
            'https://api.openai.com/v1/chat/completions',
            array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $api_key,
                    'Content-Type'  => 'application/json',
                ),
                'body'    => wp_json_encode( $body ),
                'timeout' => 20,
            )
        );

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

        $code = wp_remote_retrieve_response_code( $response );
        if ( $code < 200 || $code >= 300 ) {
            return '';
        }

        $data = json_decode( wp_remote_retrieve_body( $response ), true );
        if ( empty( $data['choices'][0]['message']['content'] ) ) {
            return '';
        }

        return trim( $data['choices'][0]['message']['content'] );
    }
}
