<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-category-assigner.php
// Description: Auto-assigns posts still in Uncategorized to the best matching AMAI category via AI - NUCLEAR+++
// Last Edited: 2026-04-24
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

class CategoryAssigner
{
    public static function register(): void
    {
        add_action('save_post', [self::class, 'onSavePost'], 25, 2);
    }

    public static function onSavePost(int $post_id, \WP_Post $post): void
    {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (wp_is_post_revision($post_id)) {
            return;
        }
        if ($post->post_status === 'auto-draft' || $post->post_status === 'trash') {
            return;
        }
        $post_type_obj = get_post_type_object($post->post_type);
        if (!$post_type_obj instanceof \WP_Post_Type || !$post_type_obj->public) {
            return;
        }

        // Only act if post is still in Uncategorized (or has no category)
        $terms = wp_get_post_terms($post_id, 'category', ['fields' => 'slugs']);
        if (!is_array($terms)) {
            return;
        }
        $non_default = array_filter($terms, fn(string $s): bool => $s !== 'uncategorized');
        if (!empty($non_default)) {
            return;
        }

        $plain = wp_strip_all_tags($post->post_content);
        if ($plain === '' && $post->post_title === '') {
            return;
        }

        $slug = self::classifyViaCore($post->post_title, $plain);
        if ($slug === null) {
            return;
        }

        $term = get_term_by('slug', $slug, 'category');
        if (!$term instanceof \WP_Term) {
            return;
        }

        wp_set_post_categories($post_id, [$term->term_id], false);
    }

    private static function classifyViaCore(string $title, string $plain): ?string
    {
        if (!defined('AMAI_HMAC_SECRET') || AMAI_HMAC_SECRET === '') {
            return null;
        }
        if (!defined('AMAI_CORE_URL') || AMAI_CORE_URL === '') {
            return null;
        }

        $method    = 'POST';
        $path      = '/api/seo/classify-category';
        $url       = rtrim(AMAI_CORE_URL, '/') . $path;
        $timestamp = (string) time();
        $nonce     = bin2hex(random_bytes(16));
        $tenant    = amai_tenant_id();
        $key_id    = 'WP_PROXY';

        $payload   = ['title' => $title, 'content' => mb_substr($plain, 0, 1500)];
        $body      = (string) json_encode($payload);
        $raw_secret = (string) get_option('amai_tenant_hmac_secret', '');
        if ($raw_secret === '') {
            return null;
        }
        $secret    = hex2bin($raw_secret);
        $body_b64  = base64_encode(hash('sha256', $body, true));
        $canonical = implode('|', [$method, $path, $timestamp, $nonce, $tenant, $key_id, $body_b64]);
        $signature = rtrim(base64_encode(hash_hmac('sha256', $canonical, $secret, true)), "\n");

        $response = wp_remote_post($url, [
            'timeout' => 20,
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Amai-Tenant'      => $tenant,
                'X-Amai-Key-Id'      => $key_id,
                'X-Amai-Timestamp'   => $timestamp,
                'X-Amai-Nonce'       => $nonce,
                'X-Amai-Body-SHA256' => $body_b64,
                'X-Amai-Signature'   => $signature,
            ],
            'body' => $body,
        ]);

        if (is_wp_error($response)) {
            error_log('[AutoMarketer AI] CategoryAssigner::classifyViaCore - wp_error: ' . $response->get_error_message());
            return null;
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        $data = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200 || !is_array($data) || empty($data['slug'])) {
            error_log('[AutoMarketer AI] CategoryAssigner::classifyViaCore - bad response ' . $code);
            return null;
        }

        return (string) $data['slug'];
    }
}
