from __future__ import annotations

from enum import Enum

from pydantic import BaseModel, Field

from broadie.factory import create_agent, create_sub_agent


class RiskLevel(str, Enum):
    phishing = "phishing"
    suspicious = "suspicious"
    not_phishing = "not_phishing"


class LinkCheckResult(BaseModel):
    url: str
    is_malicious: bool
    risk_score: int = Field(
        ge=0,
        le=100,
        description="Confidence score for maliciousness",
    )
    reason: str = Field(..., description="Why this URL was flagged or cleared")


class PhishGuardianOutput(BaseModel):
    classification: RiskLevel = Field(..., description="Phishing classification")
    risk_score: int = Field(
        ...,
        ge=0,
        le=100,
        description="Confidence score of classification",
    )
    justification: str = Field(..., description="Reasoning behind the classification")
    message_to_recipient: str = Field(
        ...,
        description="Message to display to end-user in plain language",
    )
    original_message: str = Field(..., description="Original message as received")
    links: list[LinkCheckResult] | None = Field(
        None,
        description="Analysis results for embedded links",
    )


link_checker = create_sub_agent(
    name="link_checker",
    prompt="Analyze suspicious links for phishing and return risk scores",
    output_schema=LinkCheckResult,
)

phish_guardian = create_agent(
    name="phish_guardian",
    instruction="Analyze emails for phishing risks and recommend safe handling.",
    output_schema=PhishGuardianOutput,
    channels=[
        {
            "type": "slack",
            "target": "bibt-tines-testing",
            "instructions": (
                "Format as Slack blocks using sections, dividers, and fields. "
                "Use emojis for severity (🚨 phishing, ⚠️ suspicious, ✅ safe). "
                "Include classification, risk score, justification, and the message "
                "to the recipient. If links are analyzed, list them in fields. "
                "Example Slack block structure:\n\n"
                """slack_blocks_example = [
    # Header
    {
        "type": "section",
        "text": {"type": "mrkdwn", "text": "*PhishGuardian Alert* :alert_red_light:"}
    },
    {"type": "divider"},

    # Classification and risk score
    {
        "type": "section",
        "fields": [
            {"type": "mrkdwn", "text": "*Classification:*\nPhishing"},
            {"type": "mrkdwn", "text": "*Risk Score:*\n85%"}
        ]
    },

    # Justification (italics)
    {
        "type": "section",
        "text": {"type": "mrkdwn", "text": "_Justification:_ Suspicious login link detected."}
    },

    # Message to recipient (code block)
    {
        "type": "section",
        "text": {"type": "mrkdwn", "text": "*Message to Recipient:*\n```Please do not click this link.```"}
    },

    {"type": "divider"},
    {
        "type": "section",
        "text": {"type": "mrkdwn", "text": "*Original Message:*"},
    },
    {
        "type": "context",
        "elements": [
            {"type": "mrkdwn", "text": "```Hello user, please reset your password here: http://bad-link.com...```"}
        ]
    },

    # Link analysis (if any)
    {"type": "divider"},
    {"type": "section", "text": {"type": "mrkdwn", "text": "*Link Analysis:*"}},
    {
        "type": "section",
        "fields": [
            {"type": "mrkdwn", "text": "*URL:*\nhttp://bad-link.com"},
            {"type": "mrkdwn", "text": "*Status:*\nMalicious (99%)"},
            {"type": "mrkdwn", "text": "*Reason:*\nKnown phishing domain"}
        ]
    },

    {"type": "divider"},

    # Action buttons
    {
        "type": "actions",
        "elements": [
            {
                "type": "button",
                "text": {"type": "plain_text", "text": "Create Story"},
                "style": "primary",
                "action_id": "create_story"
            },
            {
                "type": "button",
                "text": {"type": "plain_text", "text": "Ignore"},
                "style": "danger",
                "action_id": "ignore"
            }
        ]
    }
]
"""
            ),
        },
    ],
    subagents=[link_checker],
)


if __name__ == "__main__":
    import asyncio

    async def main():
        email_message = "Hello user, please reset your password here: http://bad-link.com"
        result = await phish_guardian.run(email_message)
        print(result)

    asyncio.run(main())
