<?php

namespace HaoZiTeam\AIPost\Service\Features;

defined('ABSPATH') || exit;

class AiAvatarService
{
	public static function ensure_ai_user_avatar(array $settings, int $user_id, string $fallback_avatar_url = ''): string
	{
		$user_id = (int)$user_id;
		if ($user_id <= 0) { return ''; }
		$current = (string)\get_user_meta($user_id, '_aipost_ai_avatar', true);
		$current = trim($current);
		if ($current !== '') { return $current; }

		$enabled = (bool)($settings['global_tabs']['enable_ai_comments'] ?? false);
		$avatar_enabled = (bool)($settings['global_tabs']['ai_comments_enable_avatar'] ?? false);
		if (!$enabled || !$avatar_enabled) {
			if ($fallback_avatar_url !== '') {
				\update_user_meta($user_id, '_aipost_ai_avatar', \esc_url($fallback_avatar_url));
				return (string)$fallback_avatar_url;
			}
			return '';
		}

		$remote = 'https://img.8due.com/Profile-Picture/';
		$remote = (string)\apply_filters('aipost_ai_avatar_remote_library_url', $remote, $user_id);
		$remote = trim($remote);
		if ($remote === '') {
			if ($fallback_avatar_url !== '') {
				\update_user_meta($user_id, '_aipost_ai_avatar', \esc_url($fallback_avatar_url));
				return (string)$fallback_avatar_url;
			}
			return '';
		}

		try {
			$resp = \wp_remote_get($remote, [
				'timeout' => 20,
				'redirection' => 5,
				'headers' => [
					'Accept' => 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
				],
			]);
			if (\is_wp_error($resp)) {
				throw new \Exception($resp->get_error_message());
			}
			$code = (int)\wp_remote_retrieve_response_code($resp);
			$body = (string)\wp_remote_retrieve_body($resp);
			if ($code < 200 || $code >= 300 || $body === '') {
				throw new \Exception('bad response');
			}
			$content_type = (string)\wp_remote_retrieve_header($resp, 'content-type');
			$content_type = strtolower(trim(explode(';', $content_type)[0] ?? ''));
			$ext = 'jpg';
			if ($content_type === 'image/png') { $ext = 'png'; }
			elseif ($content_type === 'image/gif') { $ext = 'gif'; }
			elseif ($content_type === 'image/webp') { $ext = 'webp'; }
			elseif ($content_type === 'image/jpeg' || $content_type === 'image/jpg') { $ext = 'jpg'; }

			$upload = \wp_upload_dir();
			$basedir = (string)($upload['basedir'] ?? '');
			$baseurl = (string)($upload['baseurl'] ?? '');
			if ($basedir === '' || $baseurl === '') {
				throw new \Exception('upload dir missing');
			}
			$dir = rtrim($basedir, '/\\') . '/aipost-avatars';
			if (!\wp_mkdir_p($dir)) {
				throw new \Exception('mkdir failed');
			}
			$hash = substr(md5($body), 0, 12);
			$filename = 'aiuser-' . $user_id . '-' . $hash . '.' . $ext;
			$filepath = rtrim($dir, '/\\') . '/' . $filename;
			$written = @file_put_contents($filepath, $body);
			if ($written === false) {
				throw new \Exception('write failed');
			}
			$url = rtrim($baseurl, '/\\') . '/aipost-avatars/' . rawurlencode($filename);
			\update_user_meta($user_id, '_aipost_ai_avatar', \esc_url($url));
			return (string)$url;
		} catch (\Throwable $e) {
			if ($fallback_avatar_url !== '') {
				\update_user_meta($user_id, '_aipost_ai_avatar', \esc_url($fallback_avatar_url));
				return (string)$fallback_avatar_url;
			}
			return '';
		}
	}
}
