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

/**
 * R-LLM SEO F02 Service
 */
function r_llm_seo_f02_store_key(): string
{
	return 'r_llm_seo_f02_items_v1';
}

function r_llm_seo_f02_current_user_id(): int
{
	$uid = function_exists('get_current_user_id') ? (int)get_current_user_id() : 0;
	return $uid > 0 ? $uid : 0;
}

function r_llm_seo_f02_store_clear(): void
{
	r_llm_seo_f02_store_set([]);
}

function r_llm_seo_f02_store_get(): array
{
	$key = r_llm_seo_f02_store_key();
	$uid = r_llm_seo_f02_current_user_id();

	$raw = null;

	if ($uid > 0) {
		$raw = get_user_meta($uid, $key, true);
	} else {
		$raw = get_option($key, null);
	}

	if (empty($raw)) return [];

	if (is_string($raw)) {
		$decoded = json_decode($raw, true);
		return is_array($decoded) ? $decoded : [];
	}

	return is_array($raw) ? $raw : [];
}

function r_llm_seo_f02_store_set(array $items): void
{
	$key = r_llm_seo_f02_store_key();
	$uid = r_llm_seo_f02_current_user_id();

	$items = array_values($items);

	if (count($items) > 300) {
		$items = array_slice($items, 0, 300);
	}

	if ($uid > 0) {
		update_user_meta($uid, $key, $items);
	} else {
		update_option($key, $items, false);
	}
}

function r_llm_seo_f02_normalize_item(array $item): array
{
	$now = current_time('mysql');

	$created_at = isset($item['created_at']) ? (string)$item['created_at'] : '';
	if ($created_at === '') $created_at = $now;

	return [
		'id'         => (string)($item['id'] ?? wp_generate_uuid4()),
		'title'      => trim((string)($item['title'] ?? '')),
		'intent'     => trim((string)($item['intent'] ?? '')),
		'score'      => (int)($item['score'] ?? 0),
		'reason'     => trim((string)($item['reason'] ?? '')),
		'is_fav'     => !empty($item['is_fav']),
		'is_created' => !empty($item['is_created']),
		'post_id'    => (int)($item['post_id'] ?? 0),
		'created_at' => $created_at,
	];
}

function r_llm_seo_f02_store_prepend_items(array $new_items): array
{
	$items = r_llm_seo_f02_store_get();

	$seen = [];
	foreach ($items as $it) {
		if (is_array($it) && !empty($it['id'])) {
			$seen[(string)$it['id']] = true;
		}
	}

	$prepend = [];
	foreach ($new_items as $it) {

		$it = r_llm_seo_f02_normalize_item(is_array($it) ? $it : []);

		if ($it['title'] === '') continue;

		if (trim((string)$it['id']) === '') {
			$it['id'] = wp_generate_uuid4();
		}

		$tries = 0;
		while (isset($seen[$it['id']])) {
			$it['id'] = wp_generate_uuid4();
			$tries++;
			if ($tries > 10) break;
		}
		$seen[$it['id']] = true;

		$prepend[] = $it;
	}

	$items = array_merge($prepend, $items);
	$items = array_slice($items, 0, 300);

	r_llm_seo_f02_store_set($items);

	return $prepend;
}

function r_llm_seo_f02_store_toggle_fav(string $id, bool $next): ?array
{
	$items = r_llm_seo_f02_store_get();
	$found = null;

	foreach ($items as &$it) {
		if (!is_array($it)) continue;
		if ((string)($it['id'] ?? '') === $id) {
			$it['is_fav'] = $next;
			$found = r_llm_seo_f02_normalize_item($it);
			$it = $found;
			break;
		}
	}
	unset($it);

	if ($found) {
		r_llm_seo_f02_store_set($items);
	}
	return $found;
}

function r_llm_seo_f02_store_delete(string $id): bool
{
	$items = r_llm_seo_f02_store_get();
	$before = count($items);

	$items = array_values(array_filter($items, function ($it) use ($id) {
		if (!is_array($it)) return true;
		return (string)($it['id'] ?? '') !== $id;
	}));

	if (count($items) === $before) return false;

	r_llm_seo_f02_store_set($items);
	return true;
}

function r_llm_seo_f02_create_draft(string $title, string $post_type = 'post'): array
{
	$title = trim($title);
	$post_type = sanitize_key($post_type ?: 'post');

	if ($title === '') {
		throw new RuntimeException(esc_html__('タイトルが空です。', 'r-llm-seo'));
	}

	if (!post_type_exists($post_type)) {
		$post_type = 'post';
	}

	$post_id = wp_insert_post([
		'post_title'  => $title,
		'post_status' => 'draft',
		'post_type'   => $post_type,
	], true);

	if (is_wp_error($post_id)) {
		throw new RuntimeException(esc_html__('投稿の作成に失敗しました。', 'r-llm-seo'));
	}

	return [
		'post_id'  => (int)$post_id,
		'edit_url' => admin_url('post.php?post=' . (int)$post_id . '&action=edit'),
	];
}

/**
 * @return array{ok:bool, items?:array<int,array>, error?:string}
 */
function r_llm_seo_f02_generate(array $keywords, int $max_length = 32): array
{
	$keywords = array_values(array_filter(array_map(function ($v) {
		return trim((string)$v);
	}, $keywords), function ($v) {
		return $v !== '';
	}));

	$max_length = max(10, min(60, (int)$max_length));

	if (empty($keywords)) {
		return ['ok' => false, 'error' => esc_html__('キーワードを入力してください。', 'r-llm-seo')];
	}

	try {
		$data = r_llm_seo_gateway_post('seo', 'F02', [
			'keywords'   => $keywords,
			'max_length' => $max_length,
		]);

		$result = $data['result'] ?? null;
		if (!is_array($result)) {
			return ['ok' => false, 'error' => esc_html__('タイトル生成に失敗しました。時間をおいて再度お試しください。', 'r-llm-seo')];
		}

		$meta = $result['meta'] ?? null;
		if (is_array($meta) && !empty($meta['error'])) {
			return ['ok' => false, 'error' => esc_html__('タイトル生成中にエラーが発生しました。時間をおいて再度お試しください。', 'r-llm-seo')];
		}

		$items = $result['items'] ?? null;
		if (!is_array($items)) {
			return ['ok' => false, 'error' => esc_html__('タイトル案の取得に失敗しました。時間をおいて再度お試しください。', 'r-llm-seo')];
		}

		if (empty($items)) {
			return ['ok' => false, 'error' => esc_html__('タイトル案を生成できませんでした。時間をおいて再度お試しください。', 'r-llm-seo')];
		}

		$norm = [];
		foreach ($items as $it) {
			if (!is_array($it)) continue;

			$title = trim((string)($it['title'] ?? ''));

			if ($title === '') {
				continue;
			}

			$norm[] = r_llm_seo_f02_normalize_item([
				'id'     => (string)($it['id'] ?? wp_generate_uuid4()),
				'title'  => $title,
				'intent' => (string)($it['intent'] ?? ''),
				'score'  => (int)($it['score'] ?? 0),
				'reason' => (string)($it['reason'] ?? ''),
			]);
		}

		if (empty($norm)) {
			return ['ok' => false, 'error' => esc_html__('有効なタイトル案を生成できませんでした。時間をおいて再度お試しください。', 'r-llm-seo')];
		}

		$prepended = r_llm_seo_f02_store_prepend_items($norm);

		return ['ok' => true, 'items' => $prepended];

	} catch (R_LLM_SEO_GatewayException $e) {
		return [
			'ok'    => false,
			'code'  => $e->code_name ?: 'GATEWAY_ERROR',
			'error' => $e->getMessage(),
		];
	} catch (Throwable $e) {
		return ['ok' => false, 'error' => esc_html__('予期しないエラーが発生しました。時間をおいて再度お試しください。', 'r-llm-seo')];
	}
}