<?php
/**
 * Shopify product JSON endpoint parser for partner product clone fallbacks.
 *
 * @package Niwa_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Niwa_AI_Admin_Partner_Product_Shopify_Endpoint_Parser {
	const MAX_RESPONSE_BYTES = 5000000;

	private $static_variant_parser;

	public function __construct( $static_variant_parser = null ) {
		$this->static_variant_parser = $static_variant_parser instanceof Niwa_AI_Admin_Partner_Product_Static_Variant_Media_Parser
			? $static_variant_parser
			: new Niwa_AI_Admin_Partner_Product_Static_Variant_Media_Parser();
	}

	public function extract_from_url( $url ) {
		$endpoint = $this->endpoint_url( $url );
		if ( '' === $endpoint ) {
			return $this->empty_result( 'URL is not a Shopify product URL candidate.' );
		}

		$response = wp_safe_remote_get(
			$endpoint,
			array(
				'timeout'             => 20,
				'redirection'         => 3,
				'limit_response_size' => self::MAX_RESPONSE_BYTES + 1,
				'user-agent'          => 'Mozilla/5.0 (compatible; NiwaAIShopifyProductEndpoint/' . ( defined( 'NIWA_AI_VERSION' ) ? NIWA_AI_VERSION : 'dev' ) . ')',
				'headers'             => array(
					'Accept' => 'application/json,text/javascript,*/*;q=0.8',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return $this->empty_result( $response->get_error_message(), $endpoint );
		}

		$status = intval( wp_remote_retrieve_response_code( $response ) );
		$body   = trim( (string) wp_remote_retrieve_body( $response ) );
		if ( strlen( $body ) > self::MAX_RESPONSE_BYTES ) {
			return $this->empty_result( 'Shopify product JSON endpoint exceeded the response size limit.', $endpoint, $status );
		}
		if ( $status < 200 || $status >= 300 || '' === $body ) {
			return $this->empty_result( 'Shopify product JSON endpoint did not return a usable response.', $endpoint, $status );
		}

		$product = json_decode( $body, true );
		if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $product ) ) {
			return $this->empty_result( 'Shopify product JSON endpoint returned invalid JSON.', $endpoint, $status );
		}

		$parsed = $this->static_variant_parser->extract_from_product_object( $product, $url, 'shopify_product_json_endpoint' );
		$parsed['endpoint_url'] = $endpoint;
		$parsed['http_status']  = $status;
		$parsed['title']        = isset( $product['title'] ) ? sanitize_text_field( (string) $product['title'] ) : '';
		$parsed['sku_hint']     = $this->first_variant_sku( $product );
		return $parsed;
	}

	private function endpoint_url( $url ) {
		$url = trim( (string) $url );
		if ( '' === $url || ! wp_http_validate_url( $url ) ) {
			return '';
		}

		$parts = wp_parse_url( $url );
		if (
			empty( $parts['scheme'] )
			|| ! in_array( strtolower( (string) $parts['scheme'] ), array( 'http', 'https' ), true )
			|| empty( $parts['host'] )
			|| empty( $parts['path'] )
			|| ! empty( $parts['user'] )
			|| ! empty( $parts['pass'] )
		) {
			return '';
		}
		$url = esc_url_raw( $url );

		$path = strtok( (string) $parts['path'], '?' );
		if ( ! preg_match( '#/products/([^/]+)#', $path, $m ) ) {
			return '';
		}

		$handle = preg_replace( '/\.js$/', '', (string) $m[1] );
		if ( '' === $handle ) {
			return '';
		}

		return $parts['scheme'] . '://' . $parts['host'] . '/products/' . rawurlencode( $handle ) . '.js';
	}

	private function first_variant_sku( $product ) {
		foreach ( isset( $product['variants'] ) ? (array) $product['variants'] : array() as $variant ) {
			if ( is_array( $variant ) && ! empty( $variant['sku'] ) ) {
				return sanitize_text_field( (string) $variant['sku'] );
			}
		}
		return '';
	}

	private function empty_result( $warning, $endpoint = '', $status = 0 ) {
		return array(
			'source_variations' => array(),
			'images'            => array(),
			'warnings'          => array( $warning ),
			'source'            => '',
			'endpoint_url'      => $endpoint,
			'http_status'       => intval( $status ),
			'title'             => '',
			'sku_hint'          => '',
		);
	}
}
