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

/**
 * R-LLM SEO F01 Service
 */

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

function r_llm_seo_f01_build_analysis_payload(string $current_title, string $content, array $result): array
{
	$intent = isset($result['intent']) ? trim((string) $result['intent']) : '';

	$cur = $result['current_title'] ?? null;
	$cur_title  = $current_title;
	$cur_score  = 0;
	$cur_reason = '';

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

	$payload = [
		'intent' => $intent,
		'current_title' => [
			'title'  => $cur_title,
			'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;
		}

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

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

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

	return $payload;
}

function r_llm_seo_f01_decode_saved_analysis($raw): array
{
	$empty = [
		'ok'            => false,
		'intent'        => '',
		'current_title' => [
			'title'  => '',
			'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_title'] ?? [];
	$current_title = [
		'title'  => is_array($current) ? trim((string) ($current['title'] ?? '')) : '',
		'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;
			}

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

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

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

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

function r_llm_seo_f01_get_saved_analysis(int $post_id): array
{
	$raw = get_post_meta($post_id, '_ai_title_suggestions_full', true);
	return r_llm_seo_f01_decode_saved_analysis($raw);
}

function r_llm_seo_f01_analyze(string $current_title, string $content, string $mode): array
{
	$mode = r_llm_seo_f01_normalize_mode($mode);
	$current_title = trim($current_title);
	$content       = trim($content);

	try {
		$data = r_llm_seo_gateway_post('seo', 'F01', [
			'current_title' => $current_title,
			'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 が見つかりません（F01仕様と不一致）', 'r-llm-seo'),
				'meta'    => (isset($data['meta']) && is_array($data['meta'])) ? $data['meta'] : null,
			];
		}

		$payload = r_llm_seo_f01_build_analysis_payload($current_title, $content, $result);

		$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()
			),
		];
	}
}