<?php
namespace EncypherProvenance;

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

class Encypher_Sign_Ability
{
    private const OPTION_KEY = 'encypher_provenance_settings';

    public function get_name(): string
    {
        return 'encypher/sign';
    }

    public function get_label(): string
    {
        return __('Encypher: Sign Content', 'encypher-provenance');
    }

    public function get_description(): string
    {
        return __('Embed a C2PA-compatible cryptographic provenance signature into text content using the Encypher API. The signed text includes an invisible Unicode watermark that survives copy-paste.', 'encypher-provenance');
    }

    public function can_execute(): bool
    {
        $settings = get_option(self::OPTION_KEY, []);
        return !empty($settings['api_key']);
    }

    /**
     * @param array $args {
     *   @type string $text              Required. The text to sign.
     *   @type array  $metadata          Optional. Metadata to embed in the manifest.
     *   @type string $document_type     Optional. Override document type.
     *   @type bool   $is_ai_content     Optional. Flag for AI-generated content.
     *   @type array  $custom_assertions Optional. Custom C2PA assertions.
     *   @type string $template_id       Optional. Assertion template ID.
     * }
     * @return string|\WP_Error Signed text or WP_Error.
     */
    public function execute(array $args)
    {
        $text = $args['text'] ?? '';
        if (empty(trim($text))) {
            return new \WP_Error('encypher_sign_empty', __('Text is required to sign.', 'encypher-provenance'));
        }

        if (!$this->can_execute()) {
            return new \WP_Error('encypher_no_api_key', __('Encypher API key not configured.', 'encypher-provenance'));
        }

        // Abilities calls have no durable WordPress trigger row or native post
        // identity. Sending arbitrary text to the production signer would make
        // retries indistinguishable from intentional re-signs, so this
        // alternate seam fails closed until the Abilities API can supply a
        // server-owned persistent generation identity.
        return new \WP_Error(
            'encypher_sign_identity_required',
            __('This ability cannot sign production content without a durable WordPress post generation. Use the post signing workflow.', 'encypher-provenance')
        );
    }

    /**
     * Register this ability with the Abilities API using the WP 6.9+ core
     * signature (name + args array). MUST be called on the
     * `wp_abilities_api_init` action; the 'encypher' category is registered
     * by the plugin bootstrap on `wp_abilities_api_categories_init`.
     */
    public function register(): void
    {
        if (! function_exists('wp_register_ability')) {
            return;
        }

        // The Abilities API landed in WordPress 6.9. The plugin's core signing
        // and verification features support WordPress 6.0+, so this optional
        // integration is dispatched through a fixed local variable (guarded by
        // the function_exists() check above) rather than a literal call. A
        // direct wp_register_ability() call is reported by Plugin Check as
        // incompatible with the 6.0 floor even though the guard makes it a safe
        // no-op on older WordPress; raising "Requires at least" is rejected
        // because it would drop supported versions.
        $register_ability = 'wp_register_ability';
        $register_ability($this->get_name(), [
            'label'               => $this->get_label(),
            'description'         => $this->get_description(),
            'category'            => 'encypher',
            'execute_callback'    => [$this, 'execute'],
            'permission_callback' => [$this, 'can_execute'],
            'input_schema'        => [
                'type'       => 'object',
                'properties' => [
                    'text'              => ['type' => 'string', 'description' => __('The text to sign.', 'encypher-provenance')],
                    'metadata'          => ['type' => 'object', 'description' => __('Metadata to embed in the manifest.', 'encypher-provenance')],
                    'document_type'     => ['type' => 'string'],
                    'is_ai_content'     => ['type' => 'boolean'],
                    'custom_assertions' => ['type' => 'array'],
                    'template_id'       => ['type' => 'string'],
                ],
                'required'   => ['text'],
            ],
            'output_schema'       => [
                'type'        => 'string',
                'description' => __('The signed text with embedded provenance markers.', 'encypher-provenance'),
            ],
        ]);
    }
}
