<?php

namespace Limb_Chatbot\Includes\Services\Export\Formatters;

use Limb_Chatbot\Includes\Services\Export\Abstract_Chat_Export_Formatter;

/**
 * Class Json_Chat_Export_Formatter
 *
 * Formats chat export data as structured JSON.
 *
 * Output structure:
 * {
 *   "chatbot_id": "uuid",
 *   "chatbot_name": "string",
 *   "exported_at": "datetime",
 *   "conversations": [
 *     {
 *       "chatbot_id": "uuid",
 *       "chat_id": "uuid",
 *       "chat_topic": "string",
 *       "messages": [
 *         { "timestamp": "datetime", "role": "string", "type": "string", "content": "string" }
 *       ]
 *     }
 *   ]
 * }
 *
 * @package Limb_Chatbot\Includes\Services\Export\Formatters
 * @since 1.0.0
 */
class Json_Chat_Export_Formatter extends Abstract_Chat_Export_Formatter {

	/**
	 * Format the export data as JSON.
	 *
	 * @param array $export_data Structured export data.
	 *
	 * @return string JSON-encoded string.
	 */
	public function format( array $export_data ): string {
		$output = [
			'chatbot_id'    => $export_data['chatbot_id'] ?? '',
			'chatbot_name'  => $export_data['chatbot_name'] ?? '',
			'start_date'    => $export_data['start_date'] ?? '',
			'end_date'      => $export_data['end_date'] ?? '',
			'exported_at'   => current_time( 'mysql', true ),
			'conversations' => [],
		];

		if ( ! empty( $export_data['conversations'] ) ) {
			foreach ( $export_data['conversations'] as $conversation ) {
				$messages = [];
				foreach ( $conversation['messages'] as $message ) {
					$record       = $this->extract_message_record( $message );
					$message_data = [
						'timestamp' => $record['timestamp'],
						'role'      => $record['role'],
						'type'      => $record['type'],
						'content'   => $record['content'],
					];

					if ( ! empty( $record['sources'] ) ) {
						$message_data['sources'] = $record['sources'];
					}

					$messages[] = $message_data;
				}

				$output['conversations'][] = [
					'chatbot_id'      => $export_data['chatbot_id'] ?? '',
					'chat_id'         => $conversation['chat_uuid'] ?? '',
					'chat_topic'      => $conversation['chat_name'] ?? '',
					'created_at'      => $conversation['created_at'] ?? '',
					'last_message_at' => $conversation['last_message_at'] ?? '',
					'source'          => $conversation['source'] ?? '',
					'messages'        => $messages,
				];
			}
		}

		return wp_json_encode( $output, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_content_type(): string {
		return 'application/json';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_file_extension(): string {
		return 'json';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_type(): string {
		return 'json';
	}
}

