<?php

namespace CelerSearch\CLI;

use CelerSearch\Utilities\PortableConfig;
use WP_CLI;

/**
 * Manage CelerSearch settings via WP-CLI.
 */
class SettingsCommand {

	/**
	 * Export the celersearch_settings option as a portable JSON envelope.
	 * Index FKs are rewritten to slugs so the export survives a cross-site
	 * move.
	 *
	 * ## OPTIONS
	 *
	 * [--output=<path>]
	 * : Write JSON to this file instead of stdout.
	 *
	 * ## EXAMPLES
	 *
	 *     # Print envelope to stdout
	 *     wp celersearch settings export
	 *
	 *     # Write envelope to a file
	 *     wp celersearch settings export --output=/tmp/settings.json
	 *
	 * @when after_wp_load
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Associative arguments.
	 */
	public function export( $args, $assoc_args ) {
		try {
			$envelope = PortableConfig::export_settings();
		} catch ( \Throwable $e ) {
			WP_CLI::error( 'Export failed: ' . $e->getMessage() );
		}

		$json   = wp_json_encode( $envelope, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
		$output = WP_CLI\Utils\get_flag_value( $assoc_args, 'output', null );
		if ( $output ) {
			$bytes = file_put_contents( $output, $json );
			if ( $bytes === false ) {
				WP_CLI::error( "Could not write to {$output}" );
			}
			WP_CLI::success( sprintf( 'Wrote %d bytes to %s', $bytes, $output ) );
		} else {
			WP_CLI::log( $json );
		}
	}

	/**
	 * Import settings from a portable JSON envelope. Overwrites the
	 * celersearch_settings option on this site. Index slugs are resolved
	 * back to ids; unresolved references disable the affected search area
	 * and are reported as warnings.
	 *
	 * ## OPTIONS
	 *
	 * <file>
	 * : Path to a CelerSearch settings export file.
	 *
	 * [--yes]
	 * : Skip the overwrite confirmation prompt.
	 *
	 * ## EXAMPLES
	 *
	 *     # Interactive (asks before overwriting)
	 *     wp celersearch settings import /tmp/settings.json
	 *
	 *     # Non-interactive (e.g. CI / restore script)
	 *     wp celersearch settings import /tmp/settings.json --yes
	 *
	 * @when after_wp_load
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Associative arguments.
	 */
	public function import( $args, $assoc_args ) {
		$path = $args[0];
		if ( ! is_readable( $path ) ) {
			WP_CLI::error( "Cannot read file: {$path}" );
		}
		$contents = file_get_contents( $path );
		if ( $contents === false || $contents === '' ) {
			WP_CLI::error( "File is empty: {$path}" );
		}
		$envelope = json_decode( $contents, true );
		if ( ! is_array( $envelope ) ) {
			WP_CLI::error( "File is not valid JSON: {$path}" );
		}

		WP_CLI::confirm( 'This will overwrite the current celersearch_settings option. Continue?', $assoc_args );

		try {
			$result = PortableConfig::import_settings( $envelope );
		} catch ( \InvalidArgumentException $e ) {
			WP_CLI::error( $e->getMessage() );
		} catch ( \Throwable $e ) {
			WP_CLI::error( 'Import failed: ' . $e->getMessage() );
		}

		WP_CLI::success( 'Settings imported.' );

		if ( ! empty( $result['unresolved'] ) ) {
			WP_CLI::warning( 'Some referenced indices were not found on this site:' );
			foreach ( $result['unresolved'] as $u ) {
				WP_CLI::log( sprintf( '  - %s (slug: %s, scope: %s)', $u['label'], $u['slug'], $u['scope'] ) );
			}
		}
	}
}
