<?php
defined('ABSPATH') || exit;

/**
 * R-LLM SEO F03 Service
 */

function r_llm_seo_f03_normalize_mode(string $mode): string
{
	$mode = trim($mode);
	return in_array($mode, ['keep', 'pro'], true) ? $mode : 'keep';
}

function r_llm_seo_f03_get_target_field(): string
{
	$target_field = get_option('r_llm_seo_desc_target', 'post_excerpt');
	$target_field = is_string($target_field) ? trim($target_field) : 'post_excerpt';

	if ($target_field === '') {
		$target_field = 'post_excerpt';
	}

	return ($target_field === 'post_excerpt') ? 'post_excerpt' : sanitize_key($target_field);
}

function r_llm_seo_f03_get_current_description(int $post_id, ?WP_Post $post = null): string
{
	$target_field = r_llm_seo_f03_get_target_field();

	if ($target_field === 'post_excerpt') {
		if ($post instanceof WP_Post) {
			return (string) $post->post_excerpt;
		}

		$post = get_post($post_id);
		return ($post instanceof WP_Post) ? (string) $post->post_excerpt : '';
	}

	return (string) get_post_meta($post_id, $target_field, true);
}

function r_llm_seo_f03_build_analysis_payload(string $current_desc, array $result): array
{
	$intent = isset($result['intent']) ? trim((string) $result['intent']) : '';

	$cur = $result['current_description'] ?? null;
	$cur_desc   = $current_desc;
	$cur_score  = 0;
	$cur_reason = '';

	if (is_array($cur)) {
		if (isset($cur['description']) && is_string($cur['description']) && trim($cur['description']) !== '') {
			$cur_desc = trim((string) $cur['description']);
		}
		$cur_score  = max(0, (int) ($cur['score'] ?? 0));
		$cur_reason = trim((string) ($cur['reason'] ?? ''));
	}

	$payload = [
		'intent' => $intent,
		'current_description' => [
			'description' => $cur_desc,
			'score'       => $cur_score,
			'reason'      => $cur_reason,
		],
		'suggestions' => [],
	];

	$suggestions = $result['suggestions'] ?? [];
	if (!is_array($suggestions)) {
		return $payload;
	}

	foreach ($suggestions as $s) {
		if (!is_array($s)) {
			continue;
		}

		$desc = trim((string) ($s['description'] ?? ''));
		if ($desc === '') {
			continue;
		}

		$score = (int) ($s['score'] ?? 0);
		if ($score <= 0) {
			$score = 80;
		}

		$payload['suggestions'][] = [
			'description' => $desc,
			'score'       => $score,
			'reason'      => trim((string) ($s['reason'] ?? '')),
		];
	}

	return $payload;
}

function r_llm_seo_f03_decode_saved_analysis($raw): array
{
	$empty = [
		'ok'                  => false,
		'intent'              => '',
		'current_description' => [
			'description' => '',
			'score'       => 0,
			'reason'      => '',
		],
		'suggestions'         => [],
		'is_parse_error'      => false,
		'raw'                 => is_scalar($raw) ? (string) $raw : '',
	];

	if (!is_string($raw) || trim($raw) === '') {
		return $empty;
	}

	$data = json_decode($raw, true);
	if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
		$empty['is_parse_error'] = true;
		return $empty;
	}

	$intent = isset($data['intent']) ? trim((string) $data['intent']) : '';

	$current = $data['current_description'] ?? [];
	$current_description = [
		'description' => is_array($current) ? trim((string) ($current['description'] ?? '')) : '',
		'score'       => is_array($current) ? max(0, (int) ($current['score'] ?? 0)) : 0,
		'reason'      => is_array($current) ? trim((string) ($current['reason'] ?? '')) : '',
	];

	$normalized_suggestions = [];
	$suggestions = $data['suggestions'] ?? [];
	if (is_array($suggestions)) {
		foreach ($suggestions as $index => $item) {
			if (!is_array($item)) {
				continue;
			}

			$desc = trim((string) ($item['description'] ?? ''));
			if ($desc === '') {
				continue;
			}

			$score = (float) ($item['score'] ?? 0);
			if ($score > 0 && $score <= 10) {
				$score *= 10;
			}

			$normalized_suggestions[] = [
				'index'       => (int) $index + 1,
				'description' => $desc,
				'score'       => max(0, (int) round($score)),
				'reason'      => trim((string) ($item['reason'] ?? '')),
			];
		}
	}

	return [
		'ok'                  => true,
		'intent'              => $intent,
		'current_description' => $current_description,
		'suggestions'         => $normalized_suggestions,
		'is_parse_error'      => false,
		'raw'                 => $raw,
	];
}

function r_llm_seo_f03_get_saved_analysis(int $post_id): array
{
	$raw = get_post_meta($post_id, '_ai_desc_suggestions_full', true);
	return r_llm_seo_f03_decode_saved_analysis($raw);
}

function r_llm_seo_f03_analyze(string $current_desc, string $content, string $mode): array
{
	$mode = r_llm_seo_f03_normalize_mode($mode);
	$current_desc = trim($current_desc);
	$content      = trim($content);

	try {
		$data = r_llm_seo_gateway_post('seo', 'F03', [
			'current_description' => $current_desc,
			'content'             => $content,
			'mode'                => $mode,
		]);

		$result = $data['result'] ?? null;
		if (!is_array($result)) {
			return [
				'ok'      => false,
				'code'    => 'BAD_RESPONSE',
				'message' => esc_html__('result が見つかりません（封筒仕様と不一致）', 'r-llm-seo'),
				'meta'    => (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null,
			];
		}

		$suggestions = $result['suggestions'] ?? null;
		if (!is_array($suggestions)) {
			return [
				'ok'      => false,
				'code'    => 'BAD_RESPONSE',
				'message' => esc_html__('suggestions が見つかりません（F03仕様と不一致）', 'r-llm-seo'),
				'meta'    => (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null,
			];
		}

		$payload = r_llm_seo_f03_build_analysis_payload($current_desc, $result);

		if (empty($payload['suggestions'])) {
			return [
				'ok'      => false,
				'code'    => 'EMPTY_SUGGESTIONS',
				'message' => esc_html__('有効な提案がありません', 'r-llm-seo'),
				'meta'    => (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null,
			];
		}

		$json = wp_json_encode($payload, JSON_UNESCAPED_UNICODE);
		if (!is_string($json) || $json === '') {
			return [
				'ok'      => false,
				'code'    => 'JSON_ENCODE_FAILED',
				'message' => esc_html__('JSONの生成に失敗しました。', 'r-llm-seo'),
				'meta'    => (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null,
			];
		}

		return [
			'ok'   => true,
			'full' => $json,
			'meta' => (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null,
		];
	} catch (R_LLM_SEO_GatewayException $e) {
		return [
			'ok'      => false,
			'code'    => $e->code_name ?: 'GATEWAY_ERROR',
			'message' => $e->getMessage(),
			'meta'    => [
				'request_id'  => $e->request_id,
				'quota'       => $e->quota,
				'http_status' => $e->http_status,
			],
		];
	} catch (Throwable $e) {
		return [
			'ok'      => false,
			'code'    => 'INTERNAL_ERROR',
			'message' => sprintf(
				/* translators: %s: internal error message */
				esc_html__('INTERNAL_ERROR: %s', 'r-llm-seo'),
				$e->getMessage()
			),
		];
	}
}