<?php
namespace Crawl\Services;

use Crawl\Lib\Validator;
use Crawl\Repositories\CrawlQueueRepository;
use Crawl\Repositories\CrawlRunRepository;
use Crawl\Repositories\ProjectRepository;
use Crawl\Services\Crawler\UrlNormalizer;

class CrawlManagerService
{
    private ProjectRepository $projects;
    private CrawlRunRepository $runs;
    private CrawlQueueRepository $queue;
    private UrlNormalizer $normalizer;

    public function __construct()
    {
        $this->projects = new ProjectRepository();
        $this->runs = new CrawlRunRepository();
        $this->queue = new CrawlQueueRepository();
        $this->normalizer = new UrlNormalizer();
    }

    public function startRun(int $projectId, string $domain, int $maxDepth, int $maxPages, int $concurrency, string $userAgent): array
    {
        $project = $this->projects->find($projectId);
        if (!$project) {
            throw new \RuntimeException('Project not found');
        }

        $normalizedDomain = Validator::domain($domain);
        if ($normalizedDomain === null) {
            throw new \RuntimeException('Invalid domain');
        }

        $runId = $this->runs->create([
            'project_id' => $projectId,
            'domain' => $normalizedDomain,
            'status' => 'running',
            'started_at' => date('Y-m-d H:i:s'),
            'finished_at' => null,
            'total_pages' => 0,
            'error_message' => null,
            'max_depth' => $maxDepth,
            'max_pages' => $maxPages,
            'concurrency' => $concurrency,
            'user_agent' => $userAgent,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        $seed = $this->normalizer->normalize($normalizedDomain . '/');
        if ($seed === null) {
            throw new \RuntimeException('Unable to normalize domain');
        }

        $this->queue->enqueue($runId, $seed, $seed, 0);

        return [
            'crawl_run_id' => $runId,
            'status' => 'running',
            'domain' => $normalizedDomain,
        ];
    }
}
