from features.base_feature import BaseFeature


class ConflictFeature(BaseFeature):

    async def get_context(self, preferences_a: dict, preferences_b: dict, user_a_id: int = None, user_b_id: int = None) -> str:
        """
        Pure negotiation — no external tool calls needed.
        Inject mediation principles and relationship context.
        """
        raw_a = preferences_a.get("raw_details", {})
        raw_b = preferences_b.get("raw_details", {})

        conflict_type = (
            raw_a.get("conflict_type") or raw_b.get("conflict_type") or "general dispute"
        )
        relationship_importance = (
            raw_a.get("relationship_importance") or raw_b.get("relationship_importance") or "medium"
        )
        position_a = raw_a.get("position") or preferences_a.get("goal", "")
        position_b = raw_b.get("position") or preferences_b.get("goal", "")

        # Concession speed based on relationship importance
        concession_note = ""
        if str(relationship_importance).lower() == "high":
            concession_note = (
                "⚠️ relationship_importance=HIGH: Both agents should be MORE concessive. "
                "Preserving the relationship is MORE important than winning every point. "
                "Accept at satisfaction >= 55 (not the usual 70)."
            )
        elif str(relationship_importance).lower() == "low":
            concession_note = "relationship_importance=LOW: Negotiate firmly on merits."

        lines = [
            "CONFLICT RESOLUTION DOMAIN RULES:",
            "• Focus on UNDERLYING INTERESTS, not stated positions.",
            "• Creative compromise > splitting the difference mechanically.",
            "• Include a review/adjustment mechanism (e.g., trial period, revisit in 2 weeks).",
            "• NEVER make personal attacks or bring up unrelated past issues.",
            "• Propose solutions that both parties can say 'yes' to, even if not their first choice.",
            "• Frame resolutions as shared agreements, not winners and losers.",
        ]
        if concession_note:
            lines.append(f"\n{concession_note}")
        if conflict_type:
            lines.append(f"\nConflict type: {conflict_type}")
        if position_a:
            lines.append(f"Person A's stated position: {position_a}")
        if position_b:
            lines.append(f"Person B's stated position: {position_b}")
        if relationship_importance:
            lines.append(f"Relationship importance: {relationship_importance}")

        lines.append("\nAsk yourself: What does each person ACTUALLY need (not just what they said)?")
        lines.append("Propose something that addresses both underlying needs.")

        return "\n".join(lines)

    def format_resolution(
        self, resolution: dict, preferences_a: dict, preferences_b: dict
    ) -> str:
        status = resolution.get("status", "resolved")
        final = resolution.get("final_proposal", {})
        details = final.get("details", {})
        rounds = resolution.get("rounds_taken", "?")
        summary = resolution.get("summary", "")

        raw_a = preferences_a.get("raw_details", {})
        raw_b = preferences_b.get("raw_details", {})
        conflict_type = raw_a.get("conflict_type") or raw_b.get("conflict_type") or "Conflict"

        if status == "escalated":
            return (
                f"⚠️ *{conflict_type.title()} — Mediation Needed*\n\n"
                f"_{summary}_\n\n"
                f"Agents couldn't find a mutually agreeable resolution in {rounds} round(s). "
                f"Consider a neutral third-party mediator."
            )

        resolution_type = details.get("resolution_type") or details.get("type") or "compromise"
        terms = details.get("terms") or details.get("agreement") or []
        review_mechanism = details.get("review_mechanism") or details.get("review") or ""
        for_a = final.get("for_party_a") or details.get("for_a") or ""
        for_b = final.get("for_party_b") or details.get("for_b") or ""

        lines = [f"⚖️ *{conflict_type.title()} — Resolved!*\n"]
        lines.append(f"🤝 *Resolution type:* {resolution_type}")
        if for_a:
            lines.append(f"\n👤 *Person A gets:* {for_a}")
        if for_b:
            lines.append(f"👤 *Person B gets:* {for_b}")
        if terms and isinstance(terms, list):
            lines.append("\n📋 *Agreed terms:*")
            for term in terms[:5]:
                lines.append(f"  • {term}")
        elif terms:
            lines.append(f"📋 *Terms:* {terms}")
        if review_mechanism:
            lines.append(f"\n🔄 *Review:* {review_mechanism}")
        lines.append(f"\n⏱ Resolved in {rounds} round(s)")
        if summary and summary != "Agreement reached":
            lines.append(f"_{summary}_")

        return "\n".join(lines)
