<?php
require_once __DIR__ . '/../vendor/autoload.php';

use Blazemedia\Blackhole\Tools\DotEnv;
use Blazemedia\Blackhole\Tools\RunLogger;
use Blazemedia\Blackhole\Tools\SimpleDB;
use Blazemedia\Blackhole\OffersReaper;
use Blazemedia\Blackhole\OfferListProvider;

if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
    return;
}

class Blackhole_Command {

    public function __invoke( $args, $assoc_args ) {
        // Carica il file .env
        (new DotEnv( __DIR__ . '/../../../../../.env' ))->load();

        // Estrae gli argomenti
         // Estrae gli argomenti
         $rollback      = $assoc_args['rollback'] ?? null;
         $dry_run       = isset( $assoc_args['dry-run'] );
         $prefix        = getenv('DB_PREFIX') ?? "wp_";
         $limit         = isset( $assoc_args['limit'] ) ? absint( $assoc_args['limit'] ) : 0;
         $blog_id       = $assoc_args['blog_id'] ?? null;

        //se multisite setta il blog
        if (is_multisite() && $blog_id) {
            if (get_blog_details($blog_id)) {
                WP_CLI::log("Switching to blog ID: $blog_id");
                switch_to_blog($blog_id);
            } else {
                WP_CLI::error("The blog with ID $blog_id does not exist.");
            }
        }

        // Inizializza il database
        $db = SimpleDB::getInstance($prefix);

        if ( $dry_run ) {
            WP_CLI::log( "Dry run mode: no table writes and no post updates." );
            $provider = new OfferListProvider( $db, true );
            try {
                $provider->scan();
            } catch ( \Throwable $error ) {
                RunLogger::add(
                    'blackhole --dry-run',
                    $provider->getScannedPostsCount(),
                    0,
                    'Errore: ' . $error->getMessage()
                );
                WP_CLI::error( 'dry-run interrotto: ' . $error->getMessage() );
            }

            $candidates = $provider->getDryRunCandidates();
            $count = count( $candidates );
            $preview_limit = $limit > 0 ? $limit : 50;

            if ( $count === 0 ) {
                WP_CLI::success( "Dry run completed. No posts would be moved to blackhole." );
                return;
            }

            WP_CLI::log( "Dry run completed. {$count} posts would be moved to blackhole. Showing first {$preview_limit}:" );
            foreach ( array_slice( $candidates, 0, $preview_limit ) as $item ) {
                WP_CLI::line(
                    sprintf(
                        "- ID: %d | slug: %s | users: %d | post_type: %s | date: %s",
                        $item['ID'],
                        $item['query'],
                        $item['users'],
                        $item['post_type'],
                        date( 'Y-m-d', $item['timestamp'] )
                    )
                );
            }

            if ( $count > $preview_limit ) {
                WP_CLI::log( sprintf( "...and %d more posts not shown.", $count - $preview_limit ) );
            }

            RunLogger::add(
                'blackhole --dry-run',
                $count,
                0,
                sprintf( 'Trovati %d articoli da lavorare. Nessun articolo messo in blackhole (dry-run).', $count )
            );

            return;
        }

        $offersReaper = new OffersReaper( $db );
        if ( $rollback ) {
            $found = $db->countQueueByStatus( 'blackhole' );
            WP_CLI::log( "Resetting all posts to 'publish'" );
            $restored = $offersReaper->rollback();
            RunLogger::add(
                'blackhole --rollback',
                $found,
                0,
                sprintf( 'Ripristinati %d articoli da blackhole.', $restored )
            );
        } else {
            $found = $db->countQueueByStatus( 'publish', $limit );
            WP_CLI::log( "Setting posts to blackhole" );
            $moved = $offersReaper->blackhole( $limit );
            RunLogger::add(
                'blackhole',
                $found,
                $moved,
                sprintf( 'Trovati %d articoli da lavorare - messi in blackhole %d articoli.', $found, $moved )
            );
        }
    }
}

// Registra il comando WP-CLI
WP_CLI::add_command( 'blackhole', 'Blackhole_Command' );