"""Classifier-powered handlers: classify_turn, detect_theme_change,
classify_and_create."""
from __future__ import annotations

import json

from mcp.types import TextContent

from ...context import ServerContext
from ...utils import meets_confidence_threshold
# Late binding — see helpers.py docstring.
from active_claude_github_mcp import server as _s
from ..helpers import ok
from . import issues as issues_handlers
from . import threads as threads_handlers


async def classify_turn(ctx: ServerContext, text: str) -> list[TextContent]:
    result = _s.classify_turn(ctx.anthropic_api_key, text)
    return ok(result.model_dump())


async def detect_theme_change(
    ctx: ServerContext,
    thread_id: str,
    new_turn_text: str,
) -> list[TextContent]:
    comments = _s.get_discussion_comments(ctx.github_token, thread_id, last_n=30)
    result = _s.detect_theme_change(ctx.anthropic_api_key, comments, new_turn_text)
    return ok(result.model_dump())


async def classify_and_create(
    ctx: ServerContext,
    text: str,
    auto_create_threshold: str,
    also_post_turn: bool,
    opening_body: str,
    owner_arg: str,
    private_repo_arg: str,
) -> list[TextContent]:
    """#61 — one-call classify + auto-create + optional post_turn."""
    classification = _s.classify_turn(ctx.anthropic_api_key, text)

    created = meets_confidence_threshold(
        classification.confidence, auto_create_threshold
    )

    thread_dump: dict | None = None
    posted_turn: dict | None = None

    if created:
        body_for_thread = opening_body or text
        if classification.destination == "discussion":
            category = classification.category or "Ideas"
            thread_result = await threads_handlers.create_thread(
                ctx,
                "discussion",
                category,
                classification.suggested_title,
                body_for_thread,
                "",
                owner_arg,
                private_repo_arg,
            )
            thread_dump = json.loads(thread_result[0].text)
            new_thread_id = thread_dump["thread_id"]
            new_thread_type = "discussion"
        else:
            label = classification.issue_label or "feature"
            issue_result = await issues_handlers.create_issue_tool(
                ctx,
                classification.suggested_title,
                body_for_thread,
                [label],
                "",
                owner_arg,
                private_repo_arg,
            )
            thread_dump = json.loads(issue_result[0].text)
            new_thread_id = thread_dump["issue_id"]
            new_thread_type = "issue"

        if also_post_turn:
            turn_result = await threads_handlers.post_turn(
                ctx,
                new_thread_id,
                new_thread_type,
                "user",
                text,
                ctx.project_dir,
            )
            posted_turn = json.loads(turn_result[0].text)

    return ok(
        {
            "classification": classification.model_dump(),
            "created": created,
            "thread": thread_dump,
            "posted_turn": posted_turn,
        }
    )
