from pathlib import Path
import joblib
import importlib.resources as resources
from typing import Optional


from tone.fusion.fused_classifier import FusedClassifier

from tone.rules.persuasive_rules import (
    persuasive_rule,
    PERSUASIVE_INTENT_VERBS
)
from tone.rules.questioning_rules import questioning_rule
from tone.rules.formal_rules import formal_rule
from tone.rules.assertive_rules import (
    assertive_rule,
    ASSERTIVE_INTENT_VERBS
)
from tone.rules.authoritative_rules import (
    authoritative_rule,
    AUTHORITATIVE_INTENT_VERBS
)
from tone.rules.narrative_rules import narrative_rule
from tone.rules.negation import is_negated_intent


def _default_artifacts_path() -> Path:
    """
    Locate bundled artifacts inside the installed package.
    """
    return Path(resources.files("tone") / "artifacts")


class ToneAnalyzer:
    """
    Unified API for tone analysis (v1).
    Fully self-contained after pip install.
    """

    def __init__(self, artifacts_path: Optional[str] = None):
        self.artifacts_path = (
            Path(artifacts_path)
            if artifacts_path
            else _default_artifacts_path()
        )

        if not self.artifacts_path.exists():
            raise RuntimeError(
                f"Artifacts not found at {self.artifacts_path}"
            )

        self.persuasive = self._load(
            "persuasive_model.joblib",
            persuasive_rule,
            alpha=0.6,
            neg_fn=is_negated_intent,
            verbs=PERSUASIVE_INTENT_VERBS
        )

        self.questioning = self._load(
            "questioning_model.joblib",
            questioning_rule,
            alpha=0.8
        )

        self.formal = self._load(
            "formal_model.joblib",
            formal_rule,
            alpha=0.4
        )

        self.assertive = self._load(
            "assertive_model.joblib",
            assertive_rule,
            alpha=0.5,
            neg_fn=is_negated_intent,
            verbs=ASSERTIVE_INTENT_VERBS
        )

        self.authoritative = self._load(
            "authoritative_model.joblib",
            authoritative_rule,
            alpha=0.5,
            neg_fn=is_negated_intent,
            verbs=AUTHORITATIVE_INTENT_VERBS
        )

        self.narrative = self._load(
            "narrative_model.joblib",
            narrative_rule,
            alpha=0.6
        )

    def _load(
        self,
        filename,
        rule_fn,
        alpha,
        neg_fn=None,
        verbs=None
    ):
        path = self.artifacts_path / filename

        if not path.is_file():
            raise FileNotFoundError(f"Missing model artifact: {path}")

        model = joblib.load(path)

        return FusedClassifier(
            model=model,
            rule_fn=rule_fn,
            alpha=alpha,
            negation_fn=neg_fn,
            intent_verbs=verbs
        )

    def analyze(self, text: str) -> dict:
        """
        Analyze input text across all tone axes.
        """
        return {
            "persuasive": bool(self.persuasive.predict(text)),
            "questioning": bool(self.questioning.predict(text)),
            "formal": bool(self.formal.predict(text)),
            "assertive": bool(self.assertive.predict(text)),
            "authoritative": bool(self.authoritative.predict(text)),
            "narrative": bool(self.narrative.predict(text)),
        }
