<?php
/**
 * Bulk data export/import manager
 *
 * Orchestrates full backup exports and per-type exports for courses, modules, and slides.
 * Uses ConfigExporter for individual item serialization and ConfigRepository for data access.
 *
 * @package SlideMind
 * @since 0.4.0
 */

namespace SlideMind\Core;

if (!defined('ABSPATH')) {
	exit;
}

class BulkDataManager {

	/**
	 * @var ConfigRepository
	 */
	private $config_repository;

	/**
	 * @var ConfigExporter
	 */
	private $config_exporter;

	/**
	 * @var TemplateManager
	 */
	private $template_manager;

	/**
	 * Constructor
	 *
	 * @param ConfigRepository $repo
	 * @param ConfigExporter   $exporter
	 * @param TemplateManager  $templates
	 */
	public function __construct(ConfigRepository $repo, ConfigExporter $exporter, TemplateManager $templates) {
		$this->config_repository = $repo;
		$this->config_exporter   = $exporter;
		$this->template_manager  = $templates;
	}

	// =========================================================================
	// FULL BACKUP (Settings > Data tab)
	// =========================================================================

	/**
	 * Exports all plugin data as a structured array
	 *
	 * Includes courses (with modules+slides), orphan modules/slides,
	 * custom templates, memory definitions, and safe settings.
	 *
	 * @return array
	 */
	public function export_all(): array {
		$courses     = $this->config_repository->get_courses();
		$all_modules = $this->config_repository->get_all_modules();
		$all_slides  = $this->config_repository->get_all_slides();

		// Build course exports (each with nested modules+slides)
		// Also collect module IDs that belong to courses (from the export data, no extra query)
		$courses_data = [];
		$module_ids_in_courses = [];

		foreach ($courses as $course) {
			$data = $this->config_exporter->export_course_array($course['id']);
			if (is_wp_error($data)) {
				continue;
			}
			$courses_data[] = $data;

			// Track module IDs from the modules belonging to this course
			$course_modules = $this->config_repository->get_modules_by_course($course['id']);
			foreach ($course_modules as $m) {
				$module_ids_in_courses[$m['id']] = true;
			}
		}

		// Build set of all module IDs for orphan-slide detection
		$all_module_ids = [];
		foreach ($all_modules as $module) {
			$all_module_ids[$module['id']] = true;
		}

		// Orphan modules (no valid parent course)
		$orphan_modules = [];
		foreach ($all_modules as $module) {
			if (isset($module_ids_in_courses[$module['id']])) {
				continue;
			}
			$data = $this->config_exporter->export_module_array($module['id']);
			if (!is_wp_error($data)) {
				$orphan_modules[] = $data;
			}
		}

		// Orphan slides: slides whose parent_module_id is not in any known module
		$orphan_slides = [];
		foreach ($all_slides as $slide) {
			$parent_module_id = (int) ($slide['parent_module_id'] ?? 0);
			if ($parent_module_id > 0 && isset($all_module_ids[$parent_module_id])) {
				continue;
			}
			$data = $this->config_exporter->export_slide_array($slide['id']);
			if (!is_wp_error($data)) {
				$orphan_slides[] = $data;
			}
		}

		// Custom templates (exclude built-in)
		$templates        = $this->template_manager->get_all();
		$custom_templates = [];
		foreach ($templates as $tpl) {
			if (!empty($tpl['is_default'])) {
				continue;
			}
			$custom_templates[] = [
				'name'             => $tpl['title'],
				'slug'             => $tpl['slug'],
				'description'      => $tpl['description'],
				'icon'             => $tpl['icon'],
				'system_prompt'    => $tpl['system_prompt'],
				'temperature'      => $tpl['temperature'],
				'max_tokens'       => $tpl['max_tokens'],
				'variables'        => $tpl['variables'],
				'widget_mode'      => $tpl['widget_mode'],
				'max_turns'        => $tpl['max_turns'],
				'closing_message'  => $tpl['closing_message'],
				'opening_message'  => $tpl['opening_message'],
				'graceful_close'   => $tpl['graceful_close'],
				'output_variables' => $tpl['output_variables'],
			];
		}

		// Memory definitions
		$memory_definitions = get_option('slidemind_memory_definitions', []);

		return [
			'slidemind_export_version'  => '2.0',
			'export_type'        => 'bulk',
			'exported_at'        => gmdate('c'),
			'plugin_version'     => SLIDEMIND_VERSION,
			'courses'            => $courses_data,
			'orphan_modules'     => $orphan_modules,
			'orphan_slides'      => $orphan_slides,
			'templates'          => $custom_templates,
			'memory_definitions' => is_array($memory_definitions) ? $memory_definitions : [],
			'settings'           => $this->get_safe_settings(),
		];
	}

	// =========================================================================
	// PER-TYPE EXPORTS (list view buttons)
	// =========================================================================

	/**
	 * Exports all courses (flat, no nested modules/slides)
	 *
	 * @return array
	 */
	public function export_all_courses(): array {
		$courses = $this->config_repository->get_courses();
		$items   = [];

		foreach ($courses as $course) {
			$items[] = [
				'title'      => $course['title'],
				'theme'      => $course['theme'],
				'objectives' => $course['objectives'],
				'content'    => $course['content'],
			];
		}

		return $this->build_envelope('courses', ['courses' => $items]);
	}

	/**
	 * Exports all modules (flat, no nested slides)
	 *
	 * @return array
	 */
	public function export_all_modules(): array {
		$modules = $this->config_repository->get_all_modules();
		$items   = [];

		foreach ($modules as $module) {
			$items[] = [
				'title'               => $module['title'],
				'subject'             => $module['subject'],
				'context'             => $module['context'],
				'parent_course_title' => $module['parent_course_title'] ?? '',
			];
		}

		return $this->build_envelope('modules', ['modules' => $items]);
	}

	/**
	 * Exports all slides (flat)
	 *
	 * @return array
	 */
	public function export_all_slides(): array {
		$slides = $this->config_repository->get_all_slides();
		$items  = [];

		foreach ($slides as $slide) {
			$formatted = $this->config_exporter->format_slide_for_export($slide);
			$formatted['parent_module_title'] = $slide['parent_module_title'] ?? '';
			$formatted['parent_course_title'] = $slide['parent_course_title'] ?? '';
			$items[] = $formatted;
		}

		return $this->build_envelope('slides', ['slides' => $items]);
	}

	// =========================================================================
	// PRIVATE HELPERS
	// =========================================================================

	/**
	 * Builds the v2.0 export envelope
	 *
	 * @param string $export_type
	 * @param array  $payload
	 * @return array
	 */
	private function build_envelope(string $export_type, array $payload): array {
		return array_merge([
			'slidemind_export_version' => '2.0',
			'export_type'       => $export_type,
			'exported_at'       => gmdate('c'),
			'plugin_version'    => SLIDEMIND_VERSION,
		], $payload);
	}

	/**
	 * Returns safe settings (excludes CORS test mode, includes global provider)
	 *
	 * @return array
	 */
	private function get_safe_settings(): array {
		$settings = get_option('slidemind_settings', []);

		// Remove transient/sensitive keys
		unset($settings['cors_test_mode'], $settings['cors_test_mode_until']);

		$settings['global_provider'] = get_option('slidemind_global_provider', 'openrouter');

		return $settings;
	}
}
