<?php
namespace boru\ai\Tests\Cli;

use boru\ai\Cli\PersistencePruneCommand;
use boru\ai\Config\Config;
use boru\ai\Persistence\Db\DbConfig;
use boru\cli2\CLI;
use boru\cli2\CLIContext;
use boru\cli2\Models\Args;
use PHPUnit\Framework\TestCase;

class PersistencePruneCommandTest extends TestCase
{
    public function testHandleDefaultsToDryRunUntilExecuteFlagIsPresent()
    {
        $provider = new FakePruneCommandProvider();
        $command = new TestablePersistencePruneCommand($provider);

        $ctx = $this->makeContext(array(
            'before' => '2026-04-01',
        ));

        $command->handle($ctx);

        $this->assertTrue($provider->lastOptions['dry_run']);
        $this->assertSame('conversations', $provider->lastOptions['scope']);
    }

    public function testHandleUsesExecuteFlagToDisableDryRun()
    {
        $provider = new FakePruneCommandProvider();
        $command = new TestablePersistencePruneCommand($provider);

        $ctx = $this->makeContext(array(
            'before' => '2026-04-01',
            'scope' => 'all',
            'execute' => true,
        ));

        $command->handle($ctx);

        $this->assertFalse($provider->lastOptions['dry_run']);
        $this->assertSame('all', $provider->lastOptions['scope']);
    }

    protected function makeContext(array $params)
    {
        $cli = CLI::create('test');
        $args = new Args(array());
        $node = $cli->getRootNode();
        $ctx = new CLIContext($cli, $node, $args, array(), $params);

        $config = new Config();
        $config->persistence(array(
            'enabled' => true,
            'driver' => 'db',
        ));
        $config->db(array(
            'use' => false,
        ));

        $ctx->set('config', $config);

        return $ctx;
    }
}

class TestablePersistencePruneCommand extends PersistencePruneCommand
{
    protected $provider;

    public function __construct($provider)
    {
        $this->provider = $provider;
    }

    protected function makeProvider(DbConfig $config)
    {
        return $this->provider;
    }
}

class FakePruneCommandProvider
{
    public $lastOptions;

    public function prune(array $options = array())
    {
        $this->lastOptions = $options;

        return array(
            'scope' => $options['scope'],
            'before' => '2026-04-01 00:00:00',
            'dry_run' => $options['dry_run'],
            'conversations' => 1,
            'turns' => 2,
            'tool_calls' => 3,
            'conversation_notes' => 4,
        );
    }
}
