<?php

namespace App\Services;

use App\Models\Terminal;
use Illuminate\Support\Facades\Log;

class KnowledgeContextService
{
    private const MAX_CONTEXT_LENGTH = 2000;

    public function __construct(
        private DocumentSearchService $searchService,
    ) {}

    /**
     * 搜索知识库中的文档，返回 RAG 上下文
     */
    public function search(string $query, ?Terminal $terminal = null): array
    {
        $stationIds = $terminal?->station_id ? [$terminal->station_id] : [];

        $results = $this->searchService->search($query, $stationIds);

        if ($results->isEmpty()) {
            return ['context' => '', 'sources' => []];
        }

        $context = '';
        $sources = [];

        foreach ($results as $document) {
            $snippet = $this->extractSnippet($document);

            if (mb_strlen($context) + mb_strlen($snippet) > self::MAX_CONTEXT_LENGTH) {
                break;
            }

            $context .= $snippet . "\n\n";

            $fullContent = $document->getMarkdownContent() ?? '';
            $sources[] = [
                'title' => $document->title,
                'id' => $document->id,
                'total_lines' => $fullContent !== '' ? substr_count($fullContent, "\n") + 1 : 0,
            ];
        }

        return [
            'context' => trim($context),
            'sources' => $sources,
        ];
    }

    private function extractSnippet($document): string
    {
        $content = $document->getMarkdownContent() ?? $document->description ?? '';
        $header = "【{$document->title}】(ID:{$document->id})";

        if (mb_strlen($content) <= 500) {
            return "{$header}\n{$content}";
        }

        return "{$header}\n" . mb_substr($content, 0, 500) . '...';
    }
}
