"""Average Total Term Frequency (ATTF) scoring algorithm."""

from __future__ import annotations

from typing import Any

from jate.algorithms.base import Algorithm
from jate.features import TermFrequency
from jate.models import Candidate, Term, TermExtractionResult


class ATTF(Algorithm):
    """Average Total Term Frequency.

    ``score = ttf / df`` where *ttf* is total term frequency in corpus and
    *df* is the number of documents containing the term.
    """

    @property
    def description(self) -> str:
        return "Average Total Term Frequency: ttf / df"

    def score(
        self,
        candidates: list[Candidate],
        term_freq: TermFrequency,
        **kwargs: Any,
    ) -> TermExtractionResult:
        result = TermExtractionResult()

        for candidate in candidates:
            ttf = term_freq.get_ttf(candidate.normalized_form)
            df = term_freq.get_df(candidate.normalized_form)
            if ttf == 0 or df == 0:
                s = 0.0
            else:
                s = ttf / df
            term = Term(
                string=candidate.normalized_form,
                score=s,
                frequency=ttf,
                surface_forms=set(candidate.surface_forms),
            )
            result.add(term)

        return result.sort()
