<?php
/**
 * Tool: generate_video
 *
 * Generate a short video (~8s) with Google Veo 3 Fast and save it to
 * the user's WordPress media library. The proxy handles the long-running
 * Veo polling internally; the plugin just waits for the response.
 *
 * Heads-up: video generation takes 30-90 seconds. The chip will sit on
 * "Working on it..." for a while.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_generate_video($input, $ctx) {
    $prompt        = isset($input['prompt']) ? trim((string) $input['prompt']) : '';
    $aspect_ratio  = isset($input['aspect_ratio']) ? (string) $input['aspect_ratio'] : '';
    $filename_hint = isset($input['filename']) ? sanitize_file_name((string) $input['filename']) : '';

    if ($prompt === '') {
        return ['ok' => false, 'message' => 'I need a prompt describing what should happen in the video.'];
    }

    $url = SailWP_Copilot_Plugin::get_ai_proxy_url() . '/copilot/generate-video';
    $resp = wp_remote_post($url, [
        // Veo can take up to 4 minutes; allow generous timeout.
        'timeout' => 300,
        'headers' => array_filter([
            'Content-Type'   => 'application/json',
            'X-License-Key'  => SailWP_Copilot_Plugin::get_license_key() ?: null,
        ]),
        'body' => wp_json_encode([
            'prompt'        => $prompt,
            'aspect_ratio'  => $aspect_ratio,
        ]),
    ]);
    if (is_wp_error($resp)) {
        return ['ok' => false, 'message' => 'The video service did not respond in time. Try a shorter or simpler prompt.'];
    }
    $code    = wp_remote_retrieve_response_code($resp);
    $payload = json_decode(wp_remote_retrieve_body($resp), true);
    if ($code === 402 && is_array($payload) && !empty($payload['limit_reached'])) {
        $upgrade = !empty($payload['upgrade_url']) ? $payload['upgrade_url'] : $payload['pricing_url'];
        return [
            'ok'             => false,
            'limit_reached'  => true,
            'message'        => $payload['message'],
            'upgrade_url'    => $upgrade,
            'inline_upgrade' => $payload['inline_upgrade'] ?? null,
        ];
    }
    if ($code >= 400 || empty($payload['ok']) || empty($payload['video_b64'])) {
        $msg = is_array($payload) && !empty($payload['message']) ? $payload['message'] : 'Could not generate the video.';
        return ['ok' => false, 'message' => $msg];
    }

    $mime = isset($payload['mime']) ? (string) $payload['mime'] : 'video/mp4';
    $name = $filename_hint ?: ('sailwp-video-' . wp_generate_uuid4() . '.mp4');
    $data_url = 'data:' . $mime . ';base64,' . $payload['video_b64'];

    $media = swcp_save_media_from_dataurl($data_url, $name, $mime);
    if (!$media || empty($media['url'])) {
        return ['ok' => false, 'message' => 'Generated the video but could not save it to your media library.'];
    }

    return [
        'ok'              => true,
        'message'         => 'Generated and added to your media library: ' . esc_html($media['url']),
        'attachment_id'   => (int) $media['id'],
        'url'             => $media['url'],
        'view_url'        => $media['url'],
        'mime'            => $mime,
        'duration_seconds'=> isset($payload['duration_seconds']) ? (int) $payload['duration_seconds'] : 8,
    ];
}
