<?php

namespace App\Commands;

use App\Libraries\GiteaSyncService;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class SyncGiteaIncremental extends BaseCommand
{
	protected $group = 'Gitea';
	protected $name = 'gitea:sync-incremental';
	protected $description = 'Incremental sync from Gitea (default last 1 day). Usage: php spark gitea:sync-incremental [days]';

	public function run(array $params)
	{
		$days = isset($params[0]) ? (int) $params[0] : 1;
		if ($days < 1) {
			$days = 1;
		}

		CLI::write('Starting Gitea incremental sync (last ' . $days . ' day)...', 'yellow');

		$service = new GiteaSyncService();
		$result = $service->syncIncremental($days);

		if (!($result['success'] ?? false)) {
			CLI::error('Sync failed: ' . ($result['message'] ?? 'Unknown error'));
			return;
		}

		$stats = $result['stats'] ?? [];
		CLI::write('Sync done.', 'green');
		CLI::write('Mode: ' . ($stats['mode'] ?? 'incremental'));
		CLI::write('Since: ' . ($stats['since'] ?? '-'));
		CLI::write('Users: ' . ($stats['users_synced'] ?? 0));
		CLI::write('Repositories: ' . ($stats['repositories_synced'] ?? 0));
		CLI::write('Commits: ' . ($stats['commits_synced'] ?? 0));
		CLI::write('Pull Requests: ' . ($stats['pull_requests_synced'] ?? 0));

		$errors = $stats['errors'] ?? [];
		if (!empty($errors)) {
			CLI::newLine();
			CLI::write('Warnings / Errors:', 'yellow');
			foreach ($errors as $error) {
				CLI::write('- ' . $error, 'light_red');
			}
		}
	}
}
