<?php

namespace App\Commands;

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

class SyncFigmaIncremental extends BaseCommand
{
	protected $group = 'Figma';
	protected $name = 'figma:sync-incremental';
	protected $description = 'Incremental sync from single Figma file (default last 1 day). Usage: php spark figma:sync-incremental [days]';

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

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

		$service = new FigmaSyncService();
		$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('Files: ' . ($stats['files_synced'] ?? 0));
		CLI::write('Snapshots: ' . ($stats['versions_synced'] ?? 0));
		CLI::write('Comments: ' . ($stats['comments_synced'] ?? 0));

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