<?php
/**
 * Tool: generate_music
 *
 * Generate a ~30-second music clip with Google Lyria 2 and save it to
 * the user's WordPress media library. Useful for hero-section background
 * music or ambient soundtracks.
 *
 * Heads-up: Lyria 2 is a preview model on Google's side. The endpoint
 * may sometimes refuse generation or return errors; the plugin returns
 * those friendly to the chat instead of crashing the rail.
 */
if (!defined('ABSPATH')) exit;

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

    if ($prompt === '') {
        return ['ok' => false, 'message' => 'I need a prompt describing the music. Mood, instruments, tempo, anything.'];
    }

    $url = SailWP_Copilot_Plugin::get_ai_proxy_url() . '/copilot/generate-music';
    $resp = wp_remote_post($url, [
        'timeout' => 120,
        'headers' => array_filter([
            'Content-Type'   => 'application/json',
            'X-License-Key'  => SailWP_Copilot_Plugin::get_license_key() ?: null,
        ]),
        'body' => wp_json_encode(['prompt' => $prompt]),
    ]);
    if (is_wp_error($resp)) {
        return ['ok' => false, 'message' => 'The music service did not respond. Try again in a moment.'];
    }
    $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['audio_b64'])) {
        $msg = is_array($payload) && !empty($payload['message']) ? $payload['message'] : 'Could not generate music. Lyria 2 is a preview model and sometimes refuses; try a different vibe.';
        return ['ok' => false, 'message' => $msg];
    }

    $mime = isset($payload['mime']) ? (string) $payload['mime'] : 'audio/mp3';
    $ext  = preg_match('#audio/(\w+)#', $mime, $m) ? strtolower($m[1]) : 'mp3';
    if ($ext === 'mpeg') $ext = 'mp3';
    $name = $filename_hint ?: ('sailwp-music-' . wp_generate_uuid4() . '.' . $ext);
    $data_url = 'data:' . $mime . ';base64,' . $payload['audio_b64'];

    $media = swcp_save_media_from_dataurl($data_url, $name, $mime);
    if (!$media || empty($media['url'])) {
        return ['ok' => false, 'message' => 'Generated the music 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'] : 30,
    ];
}
