"""Action nodes for GitHub operations."""

from beneissue.graph.state import IssueState
from beneissue.integrations.github import get_github_client


def apply_labels_node(state: IssueState) -> dict:
    """Apply labels and assignee to the issue on GitHub."""
    gh = get_github_client()
    repo = gh.get_repo(state["repo"])
    issue = repo.get_issue(state["issue_number"])

    # Add labels
    labels_to_add = state.get("labels_to_add", [])
    if labels_to_add:
        for label in labels_to_add:
            try:
                issue.add_to_labels(label)
            except Exception:
                # Label might not exist, skip
                pass

    # Remove labels
    labels_to_remove = state.get("labels_to_remove", [])
    if labels_to_remove:
        for label in labels_to_remove:
            try:
                issue.remove_from_labels(label)
            except Exception:
                # Label might not be on issue, skip
                pass

    # Assign issue
    assignee = state.get("assignee")
    if assignee:
        try:
            issue.add_to_assignees(assignee)
        except Exception:
            # Assignee might not have permission, skip
            pass

    return {}


def post_comment_node(state: IssueState) -> dict:
    """Post a comment on the issue summarizing the analysis."""
    gh = get_github_client()
    repo = gh.get_repo(state["repo"])
    issue = repo.get_issue(state["issue_number"])

    # Build comment based on state
    comment_parts = []

    # Add triage info if invalid/duplicate/needs_info
    triage_decision = state.get("triage_decision")
    if triage_decision and triage_decision != "valid":
        comment_parts.append(f"**Triage Decision:** {triage_decision}")
        comment_parts.append(f"**Reason:** {state.get('triage_reason', 'N/A')}")
        if state.get("duplicate_of"):
            comment_parts.append(f"**Duplicate of:** #{state['duplicate_of']}")

    # Add analysis summary if available
    if state.get("analysis_summary"):
        comment_parts.append("---")
        comment_parts.append("## Analysis Summary")
        comment_parts.append(state["analysis_summary"])

        # Priority and effort estimation
        priority = state.get("priority")
        story_points = state.get("story_points")
        if priority or story_points:
            comment_parts.append("")
            if priority:
                priority_desc = {"P0": "Critical", "P1": "High", "P2": "Normal"}.get(
                    priority, priority
                )
                comment_parts.append(f"**Priority:** {priority} ({priority_desc})")
            if story_points:
                sp_desc = {
                    1: "< 1 day",
                    2: "1-2 days",
                    3: "3-5 days",
                    5: "6-10 days",
                    8: "10+ days",
                }.get(story_points, f"{story_points} points")
                comment_parts.append(f"**Estimated Effort:** {story_points} SP ({sp_desc})")

        if state.get("affected_files"):
            comment_parts.append("\n**Affected Files:**")
            for f in state["affected_files"]:
                comment_parts.append(f"- `{f}`")

        if state.get("assignee"):
            comment_parts.append(f"\n**Assigned to:** @{state['assignee']}")

        if state.get("fix_decision"):
            comment_parts.append(f"\n**Decision:** {state.get('fix_decision')}")

    # Add custom comment if provided
    if state.get("comment_to_post"):
        comment_parts.append("---")
        comment_parts.append(state["comment_to_post"])

    # Post comment if we have content
    if comment_parts:
        comment_body = "\n".join(comment_parts)
        comment_body += "\n\n---\n*🤖 Analyzed by [beneissue](https://github.com/opendataloader-project/beneissue)*"
        issue.create_comment(comment_body)

    return {}
