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

/**
 * Resolve effective translation tone.
 *
 * Priority:
 * 1) Explicit override (argument, e.g. editor / AJAX)
 * 2) Post / product meta override (_reeid_tone_override)
 * 3) Global default (first preset key)
 * 4) Hard fallback: 'neutral'
 *
 * Engine expects MACHINE KEYS only.
 */
if ( ! function_exists( 'reeid_get_effective_tone' ) ) {
    function reeid_get_effective_tone( int $post_id = 0, string $override = '' ): string {

        // 1) Explicit override (already machine key)
        $override = sanitize_key( $override );
        if ( $override !== '' ) {
            return $override;
        }

        // 2) Per-post / per-product override
        if ( $post_id > 0 ) {
            $meta = get_post_meta( $post_id, '_reeid_tone_override', true );
            if ( is_string( $meta ) && $meta !== '' ) {
                return sanitize_key( $meta );
            }
        }

        // 3) Global presets (first key = default)
        $presets = get_option( 'reeid_tone_presets', [] );
        if ( is_array( $presets ) && ! empty( $presets ) ) {
            $keys = array_keys( $presets );
            if ( ! empty( $keys[0] ) ) {
                return sanitize_key( (string) $keys[0] );
            }
        }

        // 4) Hard fallback
        return 'neutral';
    }
}

/**
 * Get available tones for UI (key => label).
 *
 * UI ONLY. Engine uses keys.
 */
if ( ! function_exists( 'reeid_get_available_tones' ) ) {
    function reeid_get_available_tones(): array {

        $presets = get_option( 'reeid_tone_presets', [] );

        if ( ! is_array( $presets ) || empty( $presets ) ) {
            return [ 'neutral' => 'Neutral' ];
        }

        $out = [];

        foreach ( $presets as $key => $label ) {
            $key = sanitize_key( (string) $key );
            if ( $key === '' ) {
                continue;
            }
            $out[ $key ] = is_string( $label ) && $label !== ''
                ? sanitize_text_field( $label )
                : ucfirst( $key );
        }

        return $out ?: [ 'neutral' => 'Neutral' ];
    }
}
