<?php
/** Wiederverwendbare, site-spezifische Agent-Skills. */

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

function wpagent_skill_schema(): array {
	return array( 'type' => 'object', 'properties' => array(
		'id' => array( 'type' => 'string' ), 'title' => array( 'type' => 'string' ), 'description' => array( 'type' => 'string' ),
		'instructions' => array( 'type' => 'string' ), 'enable_agentic' => array( 'type' => 'boolean' ),
		'enable_prompt' => array( 'type' => 'boolean' ), 'updated_at' => array( 'type' => 'string' ),
	) );
}

function wpagent_skill_summary_schema(): array {
	return array( 'type' => 'object', 'properties' => array(
		'id' => array( 'type' => 'string' ), 'title' => array( 'type' => 'string' ), 'description' => array( 'type' => 'string' ),
		'enable_agentic' => array( 'type' => 'boolean' ), 'enable_prompt' => array( 'type' => 'boolean' ), 'updated_at' => array( 'type' => 'string' ),
	) );
}

function wpagent_ability_list_skills(): array {
	$definition = wpagent_skill_ability_definition( __( 'Gespeicherte Skills auflisten', 'wp-agent-companion' ), 'wpagent_exec_list_skills', 'wpagent_perm_edit_posts', true, array(), array( 'items' => array( 'type' => 'array', 'items' => wpagent_skill_summary_schema() ), 'total' => array( 'type' => 'integer' ) ) );
	$definition['meta']['mcp'] = array(
		'uri'         => 'wpagently://site/skills',
		'annotations' => array( 'audience' => array( 'assistant' ) ),
	);
	$definition['input_schema']['default'] = array();
	return $definition;
}
function wpagent_ability_get_skill(): array {
	return wpagent_skill_ability_definition( __( 'Gespeicherten Skill lesen', 'wp-agent-companion' ), 'wpagent_exec_get_skill', 'wpagent_perm_edit_posts', true, array( 'id' => array( 'type' => 'string' ) ), array( 'skill' => wpagent_skill_schema() ), array( 'id' ) );
}
function wpagent_ability_upsert_skill(): array {
	return wpagent_skill_ability_definition( __( 'Skill speichern', 'wp-agent-companion' ), 'wpagent_exec_upsert_skill', 'wpagent_perm_manage_options', false, array( 'id' => array( 'type' => 'string' ), 'title' => array( 'type' => 'string' ), 'description' => array( 'type' => 'string' ), 'instructions' => array( 'type' => 'string' ), 'enable_agentic' => array( 'type' => 'boolean' ), 'enable_prompt' => array( 'type' => 'boolean' ) ), array( 'skill' => wpagent_skill_schema(), 'verified' => array( 'type' => 'boolean' ) ), array( 'id', 'title', 'instructions' ) );
}
function wpagent_ability_delete_skill(): array {
	return wpagent_skill_ability_definition( __( 'Skill löschen', 'wp-agent-companion' ), 'wpagent_exec_delete_skill', 'wpagent_perm_manage_options', false, array( 'id' => array( 'type' => 'string' ) ), array( 'id' => array( 'type' => 'string' ), 'deleted' => array( 'type' => 'boolean' ) ), array( 'id' ), true );
}

/**
 * Liefert die Namen aller Site-Skills, die als native MCP-Prompts angeboten
 * werden. Die Ability bleibt getrennt vom gleichnamigen Skill-Tool, damit der
 * Adapter sie nicht versehentlich zusätzlich unter tools/list exponiert.
 *
 * @return string[]
 */
function wpagent_companion_site_skill_prompt_ability_names(): array {
	$names = array();
	foreach ( wpagent_normalized_skills() as $skill ) {
		if ( ! $skill['enable_prompt'] ) {
			continue;
		}
		$names[] = 'wp-agent/site-skill-' . $skill['id'];
	}
	return $names;
}

/** @return array<string,mixed> */
function wpagent_companion_site_skill_prompt_definition( string $id ): array {
	$skills = wpagent_normalized_skills();
	$skill  = $skills[ $id ] ?? array();
	$description = (string) ( $skill['description'] ?? '' );
	if ( '' === $description ) {
		$description = sprintf(
			/* translators: %s: site skill title. */
			__( 'Site-spezifische Arbeitsanweisung: %s', 'wp-agent-companion' ),
			(string) ( $skill['title'] ?? $id )
		);
	}

	return array(
		'label'               => (string) ( $skill['title'] ?? $id ),
		'description'         => $description,
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'properties' => array(), 'default' => array() ),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'text'        => array( 'type' => 'string' ),
				'description' => array( 'type' => 'string' ),
			),
			'required'   => array( 'text', 'description' ),
		),
		'execute_callback'    => static fn( $input = array() ) => wpagent_exec_site_skill_prompt( array( 'id' => $id ) ),
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array(
			'mcp'         => array( 'public' => true, 'type' => 'prompt' ),
			'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ),
		),
	);
}

/** @return array{text:string,description:string}|WP_Error */
function wpagent_exec_site_skill_prompt( $input ) {
	$id = wpagent_state_id( is_array( $input ) ? ( $input['id'] ?? '' ) : '' );
	if ( is_wp_error( $id ) ) {
		return $id;
	}
	$skill = wpagent_normalized_skills()[ $id ] ?? null;
	if ( null === $skill ) {
		return new WP_Error( 'wpagent_skill_not_found', __( 'Skill nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	if ( ! $skill['enable_prompt'] ) {
		return new WP_Error( 'wpagent_skill_prompt_disabled', __( 'Dieser Skill ist für direkte Prompts deaktiviert.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	return array( 'text' => $skill['instructions'], 'description' => $skill['description'] );
}

function wpagent_companion_register_site_skill_prompts(): void {
	foreach ( wpagent_companion_site_skill_prompt_ability_names() as $name ) {
		$id = substr( $name, strlen( 'wp-agent/site-skill-' ) );
		wp_register_ability( $name, wpagent_companion_site_skill_prompt_definition( $id ) );
	}
}

function wpagent_skill_ability_definition( string $label, string $callback, string $permission, bool $readonly, array $input, array $output, array $required = array(), bool $destructive = false ): array {
	$input_schema = array( 'type' => 'object', 'properties' => $input );
	if ( $required ) {
		$input_schema['required'] = $required;
	}
	return array(
		'label' => $label, 'description' => __( 'Verwaltet begrenzte, site-spezifische Arbeitsanweisungen für Agent-Läufe.', 'wp-agent-companion' ), 'category' => 'wp-agent',
		'input_schema' => $input_schema, 'output_schema' => array( 'type' => 'object', 'properties' => $output ),
		'execute_callback' => $callback, 'permission_callback' => $permission,
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => $readonly, 'destructive' => $destructive, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|null */
function wpagent_normalize_stored_skill( $value ): ?array {
	if ( ! is_array( $value ) ) {
		return null;
	}
	$id = wpagent_state_id( $value['id'] ?? '' );
	if ( is_wp_error( $id ) ) {
		return null;
	}
	$normalized = array( 'id' => $id );
	foreach ( array( 'title' => 150, 'description' => 1000, 'instructions' => 20000 ) as $field => $limit ) {
		$normalized[ $field ] = wpagent_state_text( $value[ $field ] ?? '', $limit, $field );
		if ( is_wp_error( $normalized[ $field ] ) ) {
			return null;
		}
	}
	$normalized['enable_agentic'] = ! array_key_exists( 'enable_agentic', $value ) || true === $value['enable_agentic'];
	$normalized['enable_prompt']  = ! array_key_exists( 'enable_prompt', $value ) || true === $value['enable_prompt'];
	$normalized['updated_at'] = wpagent_state_text( $value['updated_at'] ?? '', 100, 'updated_at' );
	if ( is_wp_error( $normalized['updated_at'] ) ) {
		return null;
	}
	return '' !== $normalized['title'] && '' !== $normalized['instructions'] ? $normalized : null;
}

/** @return array<string,array<string,mixed>> */
function wpagent_normalized_skills(): array {
	$normalized = array();
	foreach ( wpagent_state_array_option( WPAGENT_COMPANION_OPT_SKILLS ) as $value ) {
		$skill = wpagent_normalize_stored_skill( $value );
		if ( null !== $skill ) {
			$normalized[ $skill['id'] ] = $skill;
		}
	}
	return $normalized;
}

function wpagent_exec_list_skills( $input = array() ): array {
	$skills = array_values( wpagent_normalized_skills() );
	usort( $skills, static fn( array $a, array $b ): int => strcasecmp( $a['title'], $b['title'] ) );
	$items = array_map(
		static function ( array $skill ): array {
			unset( $skill['instructions'] );
			return $skill;
		},
		$skills
	);
	return array( 'items' => $items, 'total' => count( $items ) );
}

/** @return array|WP_Error */
function wpagent_exec_get_skill( $input ) {
	$id = wpagent_state_id( is_array( $input ) ? ( $input['id'] ?? '' ) : '' );
	if ( is_wp_error( $id ) ) {
		return $id;
	}
	$skills = wpagent_normalized_skills();
	return isset( $skills[ $id ] ) ? array( 'skill' => $skills[ $id ] ) : new WP_Error( 'wpagent_skill_not_found', __( 'Skill nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
}

/** @return array|WP_Error */
function wpagent_exec_upsert_skill( $input ) {
	$input = is_array( $input ) ? $input : array();
	$id    = wpagent_state_id( $input['id'] ?? '' );
	if ( is_wp_error( $id ) ) {
		return $id;
	}
	$values = array();
	foreach ( array( 'title' => 150, 'description' => 1000, 'instructions' => 20000 ) as $field => $limit ) {
		$values[ $field ] = wpagent_state_text( $input[ $field ] ?? '', $limit, $field );
		if ( is_wp_error( $values[ $field ] ) ) {
			return $values[ $field ];
		}
	}
	foreach ( array( 'enable_agentic', 'enable_prompt' ) as $field ) {
		if ( array_key_exists( $field, $input ) && ! is_bool( $input[ $field ] ) ) {
			return new WP_Error( 'wpagent_skill_bad_flag', __( 'Skill-Schalter müssen boolesche Werte sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$values[ $field ] = ! array_key_exists( $field, $input ) || true === $input[ $field ];
	}
	if ( '' === $values['title'] || '' === $values['instructions'] ) {
		return new WP_Error( 'wpagent_skill_missing_content', __( 'title und instructions dürfen nicht leer sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$skills = wpagent_normalized_skills();
	if ( ! isset( $skills[ $id ] ) && count( $skills ) >= 100 ) {
		return new WP_Error( 'wpagent_skill_limit', __( 'Es können höchstens 100 Skills gespeichert werden.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$skill = array_merge( array( 'id' => $id ), $values, array( 'updated_at' => wpagent_state_now() ) );
	$skills[ $id ] = $skill;
	$persisted = wpagent_state_persist_options(
		array( WPAGENT_COMPANION_OPT_SKILLS => $skills ),
		'wpagent_skill_persist_failed',
		__( 'Skill konnte nicht verifiziert gespeichert werden.', 'wp-agent-companion' )
	);
	if ( is_wp_error( $persisted ) ) {
		return $persisted;
	}
	return array( 'skill' => $skill, 'verified' => true );
}

/** @return array|WP_Error */
function wpagent_exec_delete_skill( $input ) {
	$id = wpagent_state_id( is_array( $input ) ? ( $input['id'] ?? '' ) : '' );
	if ( is_wp_error( $id ) ) {
		return $id;
	}
	$skills  = wpagent_normalized_skills();
	$deleted = isset( $skills[ $id ] );
	unset( $skills[ $id ] );
	$persisted = wpagent_state_persist_options(
		array( WPAGENT_COMPANION_OPT_SKILLS => $skills ),
		'wpagent_skill_persist_failed',
		__( 'Skill konnte nicht verifiziert gelöscht werden.', 'wp-agent-companion' )
	);
	if ( is_wp_error( $persisted ) ) {
		return $persisted;
	}
	return array( 'id' => $id, 'deleted' => $deleted );
}
