<?php
/** Ability: wp-agent/get-term-seo-meta. */

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

function wpagent_ability_get_term_seo_meta(): array {
	return array(
		'label' => __( 'Term-SEO lesen', 'wp-agent-companion' ),
		'description' => __( 'Liest Titel, Description, Fokus-Keyword, Canonical, Robots und Social-Texte eines öffentlichen Terms über Rank Math, Yoast oder SEOPress und liefert einen Konflikthash.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array(
				'term_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'taxonomy' => array( 'type' => 'string', 'pattern' => '^[a-z0-9_-]+$' ),
			),
			'required' => array( 'term_id', 'taxonomy' ),
			'additionalProperties' => false,
		),
		'output_schema' => array(
			'type' => 'object',
			'properties' => wpagent_term_seo_output_properties(),
			'required' => array_keys( wpagent_term_seo_output_properties() ),
			'additionalProperties' => false,
		),
		'execute_callback' => 'wpagent_exec_get_term_seo_meta',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array(
			'show_in_rest' => true,
			'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ),
		),
	);
}

/** @param mixed $input */
function wpagent_exec_get_term_seo_meta( $input ) {
	$input    = is_array( $input ) ? $input : array();
	$term_id  = (int) ( $input['term_id'] ?? 0 );
	$taxonomy = sanitize_key( (string) ( $input['taxonomy'] ?? '' ) );
	$target   = wpagent_term_seo_target( $term_id, $taxonomy );
	if ( is_wp_error( $target ) ) {
		return $target;
	}
	$plugin    = wpagent_detect_seo_plugin();
	$supported = wpagent_term_seo_provider_supported( $plugin );
	if ( is_wp_error( $supported ) ) {
		return $supported;
	}
	return wpagent_read_term_seo_meta( $term_id, $taxonomy, $plugin );
}
