<?php
namespace boru\ai\Cli;

use boru\ai\Persistence\Db\DbConfig;
use boru\ai\Persistence\Db\DbConnection;
use boru\ai\Persistence\Db\DbPersistenceProvider;
use boru\cli2\CLIContext;
use boru\cli2\Contracts\CommandDescriptionInterface;
use boru\cli2\Contracts\CommandInterface;
use boru\cli2\Contracts\CommandParamsInterface;
use boru\cli2\Params\Flag;
use boru\cli2\Params\Option;

class PersistencePruneCommand implements CommandInterface, CommandParamsInterface, CommandDescriptionInterface
{
    public function name()
    {
        return 'persistence:prune';
    }

    public function description()
    {
        return 'Prune persisted DB rows older than a cutoff; defaults to dry-run unless --execute is passed';
    }

    public function commandParams()
    {
        return array(
            Option::create('*b|before|Delete rows older than this timestamp or strtotime-compatible string'),
            Option::create('s|scope|Prune scope: conversations, turns, tool_calls, or all'),
            Flag::create('execute|execute|Actually delete rows instead of only previewing counts'),
            Flag::create('n|dry-run|Force preview mode even if execute would otherwise be used'),
        );
    }

    public function handle(CLIContext $ctx)
    {
        $config = DbConfig::fromConfig($ctx->get('config'));
        if (!$config->enabled()) {
            throw new \RuntimeException('Persistence pruning requires persistence.enabled=true');
        }
        if ($config->driver() !== 'db') {
            throw new \RuntimeException('Persistence pruning currently supports only the DB persistence driver');
        }

        $execute = $ctx->get('execute') ? true : false;
        $dryRun = $ctx->get('dry-run') ? true : !$execute;
        $scope = $ctx->get('scope', 'conversations');

        $provider = $this->makeProvider($config);
        $summary = $provider->prune(array(
            'before' => $ctx->get('before'),
            'scope' => $scope,
            'dry_run' => $dryRun,
        ));

        $ctx->output(($dryRun ? 'Dry run' : 'Prune complete') . ':');
        $ctx->output('  Scope: ' . $summary['scope']);
        $ctx->output('  Before: ' . $summary['before']);
        $ctx->output('  Conversations: ' . $summary['conversations']);
        $ctx->output('  Turns: ' . $summary['turns']);
        $ctx->output('  Tool calls: ' . $summary['tool_calls']);
        $ctx->output('  Conversation notes: ' . $summary['conversation_notes']);

        return true;
    }

    protected function makeProvider(DbConfig $config)
    {
        return new DbPersistenceProvider(new DbConnection($config));
    }
}
