<?php
namespace Mamba\CLI;

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

/**
 * WP-CLI commands for Mamba Cache
 *
 * Usage examples:
 *  wp mamba purge all
 *  wp mamba purge url https://example.com/shop/ --and-warm
 *  wp mamba purge urls /path/to/urls.txt --and-warm
 *  wp mamba purge product 123 --and-warm
 *  wp mamba purge category 45 --and-warm
 *  wp mamba purge shop --and-warm
 *  wp mamba purge home --and-warm
 *  wp mamba purge tags product_123,category_45,store_api_products
 *  wp mamba purge store-api
 *
 *  wp mamba warmup start
 *  wp mamba warmup status
 *  wp mamba warmup cancel
 *  wp mamba warmup resume
 *  wp mamba warmup errors
 */
class Commands {
    public static function register(): void {
        if (!class_exists('\\WP_CLI')) { return; }
        \WP_CLI::add_command('mamba-cache-for-woocommerce', [__CLASS__, 'handle']);
    }

    /**
     * Entry point for `wp mamba` command.
     *
     * @param array $args        Positional args.
     * @param array $assoc_args  Assoc args.
     */
    public static function handle(array $args, array $assoc_args): void {
        if (empty($args)) {
            \WP_CLI::line('Usage: wp mamba <purge|warmup> [subcommand] [args] [--and-warm]');
            return;
        }
        $cmd = strtolower((string)$args[0]);
        $sub = $args[1] ?? '';
        switch ($cmd) {
            case 'purge':
                self::purge(array_slice($args, 1), $assoc_args);
                break;
            case 'warmup':
                self::warmup(array_slice($args, 1), $assoc_args);
                break;
            default:
                \WP_CLI::error('Unknown command: ' . $cmd);
        }
    }

    /**
     * Handle purge commands
     */
    private static function purge(array $args, array $assoc): void {
        $sub = isset($args[0]) ? strtolower((string)$args[0]) : '';
        $and_warm = isset($assoc['and-warm']);

        try {
            switch ($sub) {
                case 'all':
                    \Mamba\Modules\Caching\Services\Invalidation::clearAll();
                    \WP_CLI::success('Cleared all page cache and related markers.');
                    break;

                case 'store-api':
                    \Mamba\Modules\Caching\Services\Invalidation::clearStoreApi();
                    \WP_CLI::success('Cleared Store API cache.');
                    break;

                case 'url':
                    $url = (string)($args[1] ?? '');
                    if (!$url) { \WP_CLI::error('Missing URL argument.'); }
                    $url = esc_url_raw($url);
                    if (!$url || strpos($url, home_url()) !== 0) { \WP_CLI::error('Invalid or external URL.'); }
                    \Mamba\Modules\Caching\Services\Invalidation::clearUrl($url);
                    if ($and_warm && get_option('mamba_enable_page_cache', 0)) {
                        \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($url);
                        \WP_CLI::log('Warmed: ' . $url);
                    }
                    \WP_CLI::success('Purged: ' . $url);
                    break;

                case 'urls':
                    $file = (string)($args[1] ?? '');
                    if (!$file || !file_exists($file)) { \WP_CLI::error('Provide a valid file path containing URLs (one per line).'); }
                    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
                    $count = 0; $warmc = 0; $skipped = 0;
                    foreach ($lines as $line) {
                        $u = esc_url_raw(trim($line));
                        if ($u && strpos($u, home_url()) === 0) {
                            \Mamba\Modules\Caching\Services\Invalidation::clearUrl($u);
                            $count++;
                            if ($and_warm && get_option('mamba_enable_page_cache', 0)) {
                                \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($u);
                                $warmc++;
                            }
                        } else {
                            $skipped++;
                        }
                    }
                    \WP_CLI::success("Purged {$count} URL(s). Warmed {$warmc}. Skipped {$skipped}.");
                    break;

                case 'product':
                    $pid = (int)($args[1] ?? 0);
                    if ($pid <= 0) { \WP_CLI::error('Missing or invalid product ID.'); }
                    \Mamba\Modules\Caching\Services\Invalidation::clearRelatedProduct($pid);
                    \WP_CLI::success('Cleared related caches for product ID ' . $pid);
                    break;

                case 'category':
                    $tid = (int)($args[1] ?? 0);
                    if ($tid <= 0) { \WP_CLI::error('Missing or invalid category term ID.'); }
                    $term = get_term($tid, 'product_cat');
                    if (!$term || is_wp_error($term)) { \WP_CLI::error('Invalid category term.'); }
                    $url = get_term_link($term);
                    if (is_wp_error($url)) { \WP_CLI::error('Failed to resolve category URL.'); }
                    \Mamba\Modules\Caching\Services\Invalidation::clearUrl($url);
                    if ($and_warm && get_option('mamba_enable_page_cache', 0)) {
                        \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($url);
                        \WP_CLI::log('Warmed: ' . $url);
                    }
                    \WP_CLI::success('Purged category ' . $tid);
                    break;

                case 'shop':
                    if (!function_exists('wc_get_page_permalink')) { \WP_CLI::error('WooCommerce not active.'); }
                    $shop = wc_get_page_permalink('shop');
                    if ($shop) {
                        \Mamba\Modules\Caching\Services\Invalidation::clearUrl($shop);
                        if ($and_warm && get_option('mamba_enable_page_cache', 0)) {
                            \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($shop);
                            \WP_CLI::log('Warmed: ' . $shop);
                        }
                        \WP_CLI::success('Purged shop page.');
                    } else {
                        \WP_CLI::error('Shop page not found.');
                    }
                    break;

                case 'home':
                    $home = home_url('/');
                    \Mamba\Modules\Caching\Services\Invalidation::clearUrl($home);
                    if ($and_warm && get_option('mamba_enable_page_cache', 0)) {
                        \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($home);
                        \WP_CLI::log('Warmed: ' . $home);
                    }
                    \WP_CLI::success('Purged homepage.');
                    break;

                case 'tags':
                    $list = (string)($args[1] ?? '');
                    if (!$list) { \WP_CLI::error('Provide comma-separated tags.'); }
                    $tags = array_values(array_filter(array_map('sanitize_key', explode(',', $list))));
                    if (empty($tags)) { \WP_CLI::error('No valid tags provided.'); }
                    do_action('mamba_purge_tags', $tags);
                    \WP_CLI::success('Purged CDN tags: ' . implode(',', $tags));
                    break;

                default:
                    \WP_CLI::line('Usage: wp mamba purge <all|store-api|url <url>|urls <file>|product <id>|category <term_id>|shop|home|tags <t1,t2,...>> [--and-warm]');
            }
        } catch (\Throwable $e) {
            \WP_CLI::error($e->getMessage());
        }
    }

    /**
     * Handle warmup commands
     */
    private static function warmup(array $args, array $assoc): void {
        $sub = isset($args[0]) ? strtolower((string)$args[0]) : '';
        switch ($sub) {
            case 'start':
                if (!get_option('mamba_enable_page_cache', 0)) { \WP_CLI::error('Page cache is not enabled.'); }
                $job = \Mamba\Modules\Caching\Services\Preload\Preloader::startJob();
                \WP_CLI::success('Warmup job started. Status: ' . ($job['status'] ?? 'unknown'));
                break;

            case 'status':
                $job = \Mamba\Modules\Caching\Services\Preload\Preloader::statusJob();
                \WP_CLI::line(json_encode($job));
                break;

            case 'cancel':
                $ok = \Mamba\Modules\Caching\Services\Preload\Preloader::cancelJob();
                \WP_CLI::success($ok ? 'Warmup job cancelled.' : 'No running job.');
                break;

            case 'resume':
                $ok = \Mamba\Modules\Caching\Services\Preload\Preloader::resumeJob();
                \WP_CLI::success($ok ? 'Warmup job resumed.' : 'No paused job to resume.');
                break;

            case 'errors':
                $errors = \Mamba\Modules\Caching\Services\Preload\Warmup\ErrorTracker::getErrors();
                \WP_CLI::line(json_encode($errors));
                break;

            default:
                \WP_CLI::line('Usage: wp mamba warmup <start|status|cancel|resume|errors>');
        }
    }
}
