from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

from rights_filter.analysis.evidence_enrichment import EnrichmentSummary


@dataclass
class ReviewEnrichmentJobSummary:
    processed: int = 0
    generated_queries: int = 0
    executed_searches: int = 0
    skipped_searches: int = 0
    provider_failures: int = 0
    summary_failures: int = 0
    failed: int = 0
    failure_reasons: list[str] = field(default_factory=list)


class ReviewEnrichmentJob:
    def __init__(self, enricher: Any) -> None:
        self.enricher = enricher

    def run(
        self,
        repository: Any,
        submission_ids: list[str],
    ) -> ReviewEnrichmentJobSummary:
        summary = ReviewEnrichmentJobSummary()
        for submission_id in submission_ids:
            try:
                result: EnrichmentSummary = self.enricher.enrich_latest(
                    repository, submission_id
                )
            except Exception as exc:
                # One submission's failure must not abort the whole batch.
                summary.processed += 1
                summary.failed += 1
                summary.failure_reasons.append(
                    "enrichment failed for " + submission_id + ": " + str(exc)
                )
                continue
            summary.processed += 1
            summary.generated_queries += result.generated_queries
            summary.executed_searches += result.executed_searches
            summary.skipped_searches += result.skipped_searches
            summary.provider_failures += result.provider_failures
            summary.summary_failures += result.summary_failures
            summary.failed += result.failed
            summary.failure_reasons.extend(result.failure_reasons)
        return summary
