<?php
/**
 * Founder identity/session utility helpers.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Founder_Identity_Helper {
	/** @var object|null */
	private $chat_agent;

	public function __construct( $chat_agent = null ) {
		$this->chat_agent = $chat_agent;
	}

	public function set_chat_agent( $chat_agent ) {
		$this->chat_agent = $chat_agent;
	}

	public function maybe_absorb_identity_from_exchange( $user_text, $reply, $context = array() ) {
		if ( ! $this->chat_agent || ! method_exists( $this->chat_agent, 'maybe_absorb_founder_identity_signal' ) ) {
			return;
		}

		$this->chat_agent->maybe_absorb_founder_identity_signal( $user_text, $reply, is_array( $context ) ? $context : array() );
	}

	public function prepend_founder_intro( $reply ) {
		if ( $this->chat_agent && method_exists( $this->chat_agent, 'build_founder_intro_text' ) ) {
			return (string) $this->chat_agent->build_founder_intro_text( $reply );
		}

		$host  = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
		$intro = is_string( $host ) && '' !== $host
			? 'I am your personal AI assistant for ' . $host
			: 'I am your personal AI assistant for this site';
		$intro .= '.';

		$reply = trim( (string) $reply );
		if ( '' === $reply ) {
			return $intro;
		}

		return $intro . "\n\n" . $reply;
	}

	public function get_founder_session_id( $chat_id ) {
		$chat_id = (string) $chat_id;
		if ( 0 === strpos( $chat_id, 'whatsapp:' ) ) {
			return 'admin-whatsapp-' . preg_replace( '/[^0-9]/', '', substr( $chat_id, 9 ) );
		}

		return 'admin-telegram-' . preg_replace( '/[^0-9\\-]/', '', $chat_id );
	}

	public function filter_history_limit( $limit, $session_id ) {
		if ( $this->is_founder_transport_session( $session_id ) ) {
			return max( intval( $limit ), 400 );
		}

		return $limit;
	}

	public function filter_history_ttl( $ttl, $session_id ) {
		if ( $this->is_founder_transport_session( $session_id ) ) {
			return max( intval( $ttl ), 90 * DAY_IN_SECONDS );
		}

		return $ttl;
	}

	private function is_founder_transport_session( $session_id ) {
		$session_id = (string) $session_id;
		foreach ( array( 'admin-telegram-', 'admin-whatsapp-', 'admin-ui-', 'founder:' ) as $prefix ) {
			if ( 0 === strpos( $session_id, $prefix ) ) {
				return true;
			}
		}

		return false;
	}
}
