<?php
/**
 * Stability AI image provider (v1 text-to-image).
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio\Providers;

defined( 'ABSPATH' ) || exit;

final class Image_Stability_Provider extends Image_Provider {

	const API = 'https://api.stability.ai/v1/generation';

	public function id() {
		return 'stability';
	}

	public function generate( $prompt, array $opts = array() ) {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'Stability AI API key is required.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$engine = $this->model ?: 'stable-diffusion-xl-1024-v1-0';
		$size   = $opts['size'] ?? '1024x1024';
		list( $w, $h ) = array_pad( array_map( 'intval', explode( 'x', $size ) ), 2, 1024 );
		$count  = max( 1, min( 4, (int) ( $opts['count'] ?? 1 ) ) );

		$prompts = array( array( 'text' => (string) $prompt, 'weight' => 1 ) );
		if ( ! empty( $opts['negative_prompt'] ) ) {
			$prompts[] = array( 'text' => (string) $opts['negative_prompt'], 'weight' => -1 );
		}

		$body = array(
			'text_prompts' => $prompts,
			'cfg_scale'    => 7,
			'width'        => $w,
			'height'       => $h,
			'samples'      => $count,
			'steps'        => 30,
		);
		if ( isset( $opts['seed'] ) && '' !== $opts['seed'] ) {
			$body['seed'] = (int) $opts['seed'];
		}

		$result = $this->post_json(
			self::API . '/' . rawurlencode( $engine ) . '/text-to-image',
			$body,
			array(
				'Authorization' => 'Bearer ' . $this->api_key,
				'Accept'        => 'application/json',
			)
		);
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$images = array();
		foreach ( (array) ( $result['artifacts'] ?? array() ) as $art ) {
			if ( ! empty( $art['base64'] ) ) {
				$bytes = base64_decode( $art['base64'], true ); // phpcs:ignore
				if ( false !== $bytes ) {
					$images[] = array( 'bytes' => $bytes, 'mime' => 'image/png' );
				}
			}
		}

		if ( empty( $images ) ) {
			return new \WP_Error( 'cpais_image_empty', __( 'Stability returned no images.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		return $images;
	}

	public function test_connection() {
		if ( '' === $this->api_key ) {
			return new \WP_Error( 'cpais_missing_key', __( 'Stability AI API key is required.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}
		$response = wp_remote_get(
			'https://api.stability.ai/v1/user/account',
			array(
				'timeout' => 15,
				'headers' => array( 'Authorization' => 'Bearer ' . $this->api_key ),
			)
		);
		if ( is_wp_error( $response ) ) {
			return $response;
		}
		$code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			return new \WP_Error( 'cpais_auth_failed', __( 'Authentication failed.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => $code ) );
		}
		return true;
	}
}
