<?php
/********************************************************************
 * Copyright (C) 2024 Darko Gjorgjijoski (https://darkog.com/)
 * Copyright (C) 2024 IDEOLOGIX MEDIA Dooel (https://ideologix.com/)
 *
 * This file is property of IDEOLOGIX MEDIA Dooel (https://ideologix.com)
 * This file is part of Vimeify Plugin - https://wordpress.org/plugins/vimeify/
 *
 * Vimeify - Formerly "WP Vimeo Videos" is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 2 of the License,
 * or (at your option) any later version.
 *
 * Vimeify - Formerly "WP Vimeo Videos" is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this plugin. If not, see <https://www.gnu.org/licenses/>.
 *
 * Code developed by Darko Gjorgjijoski <dg@darkog.com>.
 **********************************************************************/

namespace Vimeify\Core\CLI;

use Vimeify\Core\Utilities\VimeoSync;

/**
 * WP-CLI commands for Vimeify sync operations
 */
class SyncCommand {

	/**
	 * The plugin instance
	 * @var \Vimeify\Core\Plugin
	 */
	protected $plugin;

	/**
	 * The sync processor
	 * @var VimeoSync
	 */
	protected $sync;

	/**
	 * Constructor
	 *
	 * @param \Vimeify\Core\Plugin $plugin
	 */
	public function __construct( $plugin ) {
		$this->plugin = $plugin;
		$this->sync   = new VimeoSync( $plugin );
	}

	/**
	 * Sync video metadata from Vimeo
	 *
	 * Fetches video metadata from Vimeo and updates local video posts.
	 * Processes one page (100 videos) per execution.
	 *
	 * ## OPTIONS
	 *
	 * [--fresh]
	 * : Reset sync state and start from the beginning
	 *
	 * ## EXAMPLES
	 *
	 *     # Run metadata sync
	 *     wp vimeify sync metadata
	 *
	 *     # Reset and start fresh
	 *     wp vimeify sync metadata --fresh
	 *
	 * @param array $args       Positional arguments
	 * @param array $assoc_args Named arguments
	 */
	public function metadata( $args, $assoc_args ) {
		$fresh = isset( $assoc_args['fresh'] );

		if ( $fresh ) {
			\WP_CLI::log( 'Resetting metadata sync state...' );
		}

		\WP_CLI::log( 'Starting metadata sync...' );

		$synced = $this->sync->sync_metadata( $fresh );

		if ( $synced > 0 ) {
			\WP_CLI::success( sprintf( 'Synced metadata for %d videos.', $synced ) );
		} else {
			\WP_CLI::warning( 'No videos were synced. Check logs for details.' );
		}
	}

	/**
	 * Sync video status (check for deleted videos)
	 *
	 * Checks if local videos still exist on Vimeo and removes those that don't.
	 * Processes videos incrementally based on API quota.
	 *
	 * ## OPTIONS
	 *
	 * [--fresh]
	 * : Reset sync state and start from the beginning
	 *
	 * ## EXAMPLES
	 *
	 *     # Run status sync
	 *     wp vimeify sync status
	 *
	 *     # Reset and start fresh
	 *     wp vimeify sync status --fresh
	 *
	 * @param array $args       Positional arguments
	 * @param array $assoc_args Named arguments
	 */
	public function status( $args, $assoc_args ) {
		$fresh = isset( $assoc_args['fresh'] );

		if ( $fresh ) {
			\WP_CLI::log( 'Resetting status sync state...' );
		}

		\WP_CLI::log( 'Starting status sync...' );

		$deleted = $this->sync->sync_status( $fresh );

		if ( $deleted > 0 ) {
			\WP_CLI::success( sprintf( 'Deleted %d videos that no longer exist on Vimeo.', $deleted ) );
		} else {
			\WP_CLI::log( 'No videos were deleted.' );
		}
	}

	/**
	 * Run all sync operations
	 *
	 * Runs both metadata and status sync operations in sequence.
	 *
	 * ## OPTIONS
	 *
	 * [--fresh]
	 * : Reset sync state and start from the beginning
	 *
	 * ## EXAMPLES
	 *
	 *     # Run all sync operations
	 *     wp vimeify sync all
	 *
	 *     # Reset and start fresh
	 *     wp vimeify sync all --fresh
	 *
	 * @param array $args       Positional arguments
	 * @param array $assoc_args Named arguments
	 */
	public function all( $args, $assoc_args ) {
		$fresh = isset( $assoc_args['fresh'] );

		\WP_CLI::log( '=== Running all sync operations ===' );

		// Run metadata sync
		\WP_CLI::log( '' );
		\WP_CLI::log( '1. Metadata Sync' );
		$this->metadata( $args, $assoc_args );

		// Run status sync
		\WP_CLI::log( '' );
		\WP_CLI::log( '2. Status Sync' );
		$this->status( $args, $assoc_args );

		\WP_CLI::success( 'All sync operations completed.' );
	}

	/**
	 * Show sync status and statistics
	 *
	 * Displays information about the current sync state and scheduled actions.
	 *
	 * ## EXAMPLES
	 *
	 *     wp vimeify sync info
	 */
	public function info() {
		\WP_CLI::log( '=== Vimeify Sync Status ===' );
		\WP_CLI::log( '' );

		// Check if Action Scheduler is available
		if ( ! function_exists( 'as_next_scheduled_action' ) ) {
			\WP_CLI::error( 'Action Scheduler is not available.' );
			return;
		}

		// Get scheduled actions
		$actions = array(
			'vimeify_action_metadata_sync'      => 'Metadata Sync (every 10 minutes)',
			'vimeify_action_status_sync'        => 'Status Sync (every 20 minutes)',
			'vimeify_action_cleanup_pull_files' => 'Cleanup Files (hourly)',
		);

		\WP_CLI::log( 'Scheduled Actions:' );
		foreach ( $actions as $hook => $label ) {
			$next = as_next_scheduled_action( $hook, array(), 'vimeify' );
			if ( $next ) {
				$time_until = human_time_diff( time(), $next );
				\WP_CLI::log( sprintf( '  - %s: in %s (%s)', $label, $time_until, date( 'Y-m-d H:i:s', $next ) ) );
			} else {
				\WP_CLI::warning( sprintf( '  - %s: NOT SCHEDULED', $label ) );
			}
		}

		\WP_CLI::log( '' );

		// Get metadata sync state
		$metadata_sync = get_option( 'vimeify_last_metadata_sync' );
		if ( ! empty( $metadata_sync ) ) {
			\WP_CLI::log( 'Metadata Sync State:' );
			if ( isset( $metadata_sync['latest_page'] ) && isset( $metadata_sync['total_pages'] ) ) {
				$progress = round( ( $metadata_sync['latest_page'] / $metadata_sync['total_pages'] ) * 100, 2 );
				\WP_CLI::log( sprintf( '  - Page: %d / %d (%s%%)', $metadata_sync['latest_page'], $metadata_sync['total_pages'], $progress ) );
			}
			if ( isset( $metadata_sync['calls_remaining'] ) ) {
				\WP_CLI::log( sprintf( '  - API calls remaining: %d', $metadata_sync['calls_remaining'] ) );
			}
		} else {
			\WP_CLI::log( 'Metadata Sync State: Not started' );
		}

		\WP_CLI::log( '' );

		// Get status sync state
		$status_sync = get_option( 'vimeify_last_status_sync' );
		if ( ! empty( $status_sync ) ) {
			\WP_CLI::log( 'Status Sync State:' );
			if ( isset( $status_sync['last_pos'] ) && isset( $status_sync['videos'] ) ) {
				$total    = count( $status_sync['videos'] );
				$progress = $total > 0 ? round( ( $status_sync['last_pos'] / $total ) * 100, 2 ) : 0;
				\WP_CLI::log( sprintf( '  - Position: %d / %d (%s%%)', $status_sync['last_pos'], $total, $progress ) );
			}
			if ( isset( $status_sync['last_synced_at'] ) ) {
				\WP_CLI::log( sprintf( '  - Last synced: %s ago', human_time_diff( $status_sync['last_synced_at'], time() ) ) );
			}
		} else {
			\WP_CLI::log( 'Status Sync State: Not started' );
		}

		\WP_CLI::log( '' );

		// Get sync behavior setting
		$sync_behavior = $this->plugin->system()->settings()->global()->get( 'sync.sync_behavior', 'existing_only' );
		\WP_CLI::log( 'Sync Behavior:' );
		if ( $sync_behavior === 'create_all' ) {
			\WP_CLI::log( '  - Mode: Sync all videos from Vimeo and create local entries' );
		} else {
			\WP_CLI::log( '  - Mode: Update existing videos only' );
		}
	}
}
