"""Inheritance Policies — rules for cross-project memory sharing.

Determines which semantic memories qualify for global promotion,
how confidence degrades across inheritance boundaries, and which
topics are excluded from sharing.
"""

from dataclasses import dataclass, field


@dataclass
class InheritancePolicy:
    min_confidence: float = 0.7
    confidence_tax: float = 0.1
    require_pii_clean: bool = True
    max_inheritance_depth: int = 3
    recall_weight_multiplier: float = 0.7
    max_global_results: int = 5
    excluded_topics: list[str] = field(default_factory=lambda: [
        "personal", "credentials", "keys", "passwords", "secrets",
        "tokens", "private", "confidential",
    ])


def get_default_policy() -> InheritancePolicy:
    """Get policy from config settings."""
    from soagila.config import get_settings
    s = get_settings()
    return InheritancePolicy(
        min_confidence=s.inheritance_confidence_threshold,
        confidence_tax=s.inheritance_confidence_tax,
        recall_weight_multiplier=s.inheritance_recall_weight,
        max_global_results=s.inheritance_max_global_results,
    )


def should_promote_to_global(
    confidence: float,
    pii_clean: bool,
    topic_tags: list[str],
    policy: InheritancePolicy | None = None,
) -> tuple[bool, str]:
    """Check if a semantic memory qualifies for global pool promotion."""
    p = policy or get_default_policy()

    if p.require_pii_clean and not pii_clean:
        return False, "PII not verified clean"

    if confidence < p.min_confidence:
        return False, f"Confidence {confidence:.2f} < threshold {p.min_confidence}"

    lowered = [t.lower() for t in topic_tags]
    for excluded in p.excluded_topics:
        if excluded in lowered:
            return False, f"Topic '{excluded}' excluded from inheritance"

    return True, "Qualifies for global promotion"


def calculate_inherited_confidence(
    original_confidence: float,
    inheritance_depth: int = 1,
    policy: InheritancePolicy | None = None,
) -> float:
    """Apply inheritance tax to confidence score."""
    p = policy or get_default_policy()
    taxed = original_confidence - (p.confidence_tax * inheritance_depth)
    return max(taxed, 0.1)  # floor at 0.1
