"""Shared decision policy for Superpitch."""

APPROVE_THRESHOLD = 7.0
REVIEW_MARGIN = 0.45
LOW_SUPPORT_QUALITY = 0.75
MIN_USEFUL_SIMILARITY = 0.25
CONFLICT_THRESHOLD = 0.45

CORRECTION_REASON_OPTIONS = (
    "team",
    "traction",
    "market",
    "risk",
    "pricing",
    "other",
)


def default_case_context():
    return {
        "neighbor_coverage": 0.0,
        "avg_score": 5.0,
        "approve_rate": 0.5,
        "disagreement": 0.0,
        "support_quality": 0.0,
        "best_similarity": 0.0,
        "avg_similarity": 0.0,
        "real_rate": 0.0,
        "scraped_rate": 0.0,
        "conflict_flag": 0.0,
    }


def normalize_case_context(case_context=None):
    context = default_case_context()
    if case_context:
        normalized = {}
        for key, value in case_context.items():
            normalized_key = key[5:] if key.startswith("case_") else key
            normalized[normalized_key] = value
        context.update(normalized)
    return context


def recommend_review(score, case_context=None, confidence_level=None, needs_review=False, is_moonshot=False):
    context = normalize_case_context(case_context)
    reasons = []
    near_line = abs(score - APPROVE_THRESHOLD) < REVIEW_MARGIN
    risky_borderline = score >= (APPROVE_THRESHOLD - 0.35)

    if is_moonshot:
        reasons.append("moonshot profile")
    if near_line:
        reasons.append("near threshold")
    if context["conflict_flag"] >= CONFLICT_THRESHOLD:
        reasons.append("conflicting similar cases")
    if (
        risky_borderline
        and
        context["best_similarity"] >= MIN_USEFUL_SIMILARITY
        and context["support_quality"] < LOW_SUPPORT_QUALITY
    ):
        reasons.append("low-trust memory")
    if (needs_review or confidence_level == "low") and risky_borderline:
        reasons.append("low confidence")

    return bool(reasons), reasons


def decide_action(score, case_context=None, confidence_level=None, needs_review=False, is_moonshot=False):
    should_review, reasons = recommend_review(
        score,
        case_context=case_context,
        confidence_level=confidence_level,
        needs_review=needs_review,
        is_moonshot=is_moonshot,
    )
    if should_review:
        return "REVIEW", reasons
    return ("APPROVE" if score >= APPROVE_THRESHOLD else "REJECT"), reasons


def feedback_priority(score, case_context=None, confidence_level=None, needs_review=False, is_moonshot=False):
    context = normalize_case_context(case_context)
    review_flag, review_reasons = recommend_review(
        score,
        case_context=context,
        confidence_level=confidence_level,
        needs_review=needs_review,
        is_moonshot=is_moonshot,
    )
    if review_flag:
        return {"level": "high", "reasons": review_reasons}

    if abs(score - APPROVE_THRESHOLD) < 0.9:
        return {"level": "medium", "reasons": ["decision boundary"]}
    if context["best_similarity"] < 0.15:
        return {"level": "medium", "reasons": ["few useful precedents"]}
    return {"level": "low", "reasons": ["routine case"]}


def normalize_correction_reason(raw_reason):
    reason = (raw_reason or "").strip().lower()
    if reason in CORRECTION_REASON_OPTIONS:
        return reason
    aliases = {
        "founder": "team",
        "team/people": "team",
        "gtm": "traction",
        "sales": "traction",
        "category": "market",
        "competition": "market",
        "red_flags": "risk",
        "valuation": "pricing",
    }
    return aliases.get(reason, "other")
