<?php
/**
 * WhatsApp identity and reply route helpers.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_WhatsApp_Identity {
	const CHAT_JIDS_FILE = 'chat-jids.json';
	const ALIASES_FILE   = 'identity-aliases.json';

	public static function normalize_sender_id( $value ) {
		$value = trim( (string) $value );
		if ( 0 === strpos( $value, 'whatsapp:' ) ) {
			$value = substr( $value, 9 );
		}
		if ( self::is_explicit_group_route( $value ) && '' !== self::normalize_group_jid( $value ) ) {
			return '';
		}
		$value = preg_replace( '/:\d+(?=@)/', '', $value );
		$value = preg_replace( '/@(s\.whatsapp\.net|lid)$/', '', (string) $value );
		$value = preg_replace( '/:\d+$/', '', (string) $value );
		$value = preg_replace( '/[^0-9+]/', '', (string) $value );
		if ( 0 === strpos( $value, '+' ) ) {
			$value = substr( $value, 1 );
		}
		return $value;
	}

	public static function normalize_gateway_jid( $value ) {
		$value = trim( (string) $value );
		if ( 0 === strpos( $value, 'whatsapp:' ) ) {
			$value = substr( $value, 9 );
		}
		$allow_bare_group = false;
		if ( 0 === strpos( $value, 'whatsapp-group:' ) ) {
			$value = substr( $value, 15 );
			$allow_bare_group = true;
		}
		$group_jid = self::normalize_group_jid( $value, $allow_bare_group );
		if ( '' !== $group_jid ) {
			return $group_jid;
		}
		if ( preg_match( '/^([0-9]+)(?::\d+)?@(s\.whatsapp\.net|lid)$/', $value, $matches ) ) {
			return $matches[1] . '@' . $matches[2];
		}
		return '';
	}

	public static function normalize_group_jid( $value, $allow_bare = true ) {
		$value = trim( (string) $value );
		if ( 0 === strpos( $value, 'whatsapp-group:' ) ) {
			$value = substr( $value, 15 );
			$allow_bare = true;
		}
		if ( preg_match( '/^([0-9]+)@g\.us$/', $value, $matches ) ) {
			return $matches[1] . '@g.us';
		}
		if ( $allow_bare && preg_match( '/^[0-9]{6,}$/', $value ) ) {
			return $value . '@g.us';
		}

		return '';
	}

	private static function is_explicit_group_route( $value ) {
		$value = trim( (string) $value );
		return 0 === strpos( $value, 'whatsapp-group:' ) || (bool) preg_match( '/@g\.us$/', $value );
	}

	public static function canonical_sender_id( $value, $state_dir = '' ) {
		$sender = self::normalize_sender_id( $value );
		if ( '' === $sender || '' === trim( (string) $state_dir ) ) {
			return $sender;
		}

		$aliases = self::read_json_file( self::state_path( $state_dir, self::ALIASES_FILE ) );
		$current = $sender;
		$seen    = array();
		for ( $i = 0; $i < 8; $i++ ) {
			if ( isset( $seen[ $current ] ) || ! isset( $aliases[ $current ] ) ) {
				break;
			}
			$seen[ $current ] = true;
			$next             = self::normalize_sender_id( $aliases[ $current ] );
			if ( '' === $next || $next === $current ) {
				break;
			}
			$current = $next;
		}

		return $current;
	}

	public static function resolve_reply_jid( $sender, $context = array(), $state_dir = '' ) {
		$context = is_array( $context ) ? $context : array();
		foreach ( array( 'remote_jid', 'gateway_chat_jid', 'whatsapp_jid', 'phone_jid' ) as $key ) {
			if ( empty( $context[ $key ] ) ) {
				continue;
			}
			$jid = self::normalize_gateway_jid( $context[ $key ] );
			if ( '' !== $jid ) {
				return $jid;
			}
		}

		$state_dir  = trim( (string) $state_dir );
		$canonical  = self::canonical_sender_id( $sender, $state_dir );
		$direct_jid = self::normalize_gateway_jid( $sender );
		if ( '' !== $state_dir ) {
			$known = self::read_json_file( self::state_path( $state_dir, self::CHAT_JIDS_FILE ) );
			foreach ( array_unique( array( $canonical, self::normalize_sender_id( $sender ) ) ) as $key ) {
				if ( '' === $key || empty( $known[ $key ] ) ) {
					continue;
				}
				$jid = self::normalize_gateway_jid( $known[ $key ] );
				if ( '' !== $jid ) {
					return $jid;
				}
			}
		}

		if ( '' !== $direct_jid ) {
			return $direct_jid;
		}

		return '' !== $canonical ? $canonical . '@s.whatsapp.net' : '';
	}

	private static function read_json_file( $path ) {
		if ( ! is_string( $path ) || '' === $path || ! is_readable( $path ) ) {
			return array();
		}

		$raw = file_get_contents( $path );
		if ( false === $raw || '' === trim( $raw ) ) {
			return array();
		}

		$decoded = json_decode( $raw, true );
		return is_array( $decoded ) ? $decoded : array();
	}

	private static function state_path( $state_dir, $file ) {
		return rtrim( (string) $state_dir, "/\\" ) . '/' . ltrim( (string) $file, "/\\" );
	}
}
