import time
from typing import Any, Dict, List, Literal, TYPE_CHECKING
from pydantic import BaseModel, ConfigDict
from blocks_control_sdk.parsers.base_messages import BLOCKS_PROVIDER_SPECIFIC_FIELDS__IS_FINAL_MESSAGE

if TYPE_CHECKING:
    from litellm.utils import ModelResponse

class AnthropicTodo(BaseModel):
    content: str
    activeForm: str
    status: Literal["in_progress", "completed", "pending"]

    model_config = ConfigDict(extra='ignore')

class AnthropicTodoListUpdate(BaseModel):
    todos: List[AnthropicTodo]

    def __str__(self):
        pending_todos = "\n".join([f"- [ ] {todo.content}" for todo in self.todos if todo.status == "pending"])
        in_progress_todos = "\n".join([f"- [ ] {todo.content}" for todo in self.todos if todo.status == "in_progress"])
        completed_todos = "\n".join([f"- [x] {todo.content}" for todo in self.todos if todo.status == "completed"])
        return f"""### Agent Todo List

### Pending
{pending_todos}

### In Progress
{in_progress_todos}

### Completed
{completed_todos}
"""

ANTHROPIC_TOOLS__WRITE = "Write" # Args: {"file_path": "...", "content": "..."}
ANTHROPIC_TOOLS__GREP = "Grep" # Args: {"pattern": "...", "path": "..."}
ANTHROPIC_TOOLS__GLOB = "Glob" # Args: {"pattern": "..."}
ANTHROPIC_TOOLS__LS = "LS" # Args: {"path": "..."}
ANTHROPIC_TOOLS__BASH = "Bash" # Args: {"command": "..."}
ANTHROPIC_TOOLS__READ = "Read" # Args: {"file_path": "..."}
ANTHROPIC_TOOLS__TODOWRITE = "TodoWrite" # Args: {"todos": [{"id": "...", "content": "...", "status": "in_progress/completed/pending"}]}
ANTHROPIC_TOOLS__BLOCKS__CLONE_REPO = "mcp__blocks-internal-mcp__clone_repository_into_folder" # Args: {"repo_owner": "...", "repo_name": "..."}

def to_model_response(blob: Dict[str, Any], *, default_model: str = "unknown-model") -> "ModelResponse":
    from litellm.litellm_core_utils.core_helpers import map_finish_reason
    from litellm.llms.anthropic.chat.transformation import AnthropicConfig 
    from litellm.utils import ModelResponse
    from litellm.types.utils import Message
    cfg = AnthropicConfig()

    blocks_provider_specific_fields = {
        BLOCKS_PROVIDER_SPECIFIC_FIELDS__IS_FINAL_MESSAGE: False
    }

    # Normalize your "result" wrapper into an Anthropic-like completion_response
    if blob.get("type") == "result":
        completion_response = {
            "model": blob.get("model", default_model),
            "content": [{"type": "text", "text": blob.get("result", "")}],
            "usage": blob.get("usage", {}) or {},
            "stop_reason": "stop",  # sensible default
        }
        blocks_provider_specific_fields[BLOCKS_PROVIDER_SPECIFIC_FIELDS__IS_FINAL_MESSAGE] = True
    # Already in your earlier Anthropic-wrapped form: {"type":"assistant","message":{...}}
    elif blob.get("type") == "assistant" and "message" in blob:
        completion_response = blob["message"]
        completion_response.setdefault("usage", {})  # ensure key exists
        completion_response.setdefault("stop_reason", "stop")
        completion_response.setdefault("model", completion_response.get("model", default_model))
    else:
        raise ValueError("Unsupported blob shape")

    # Extract content / tool calls / thinking using LiteLLM’s helpers
    text, citations, thinking_blocks, reasoning, tool_calls = cfg.extract_response_content(completion_response)

    mr = ModelResponse()
    mr.choices[0].message = Message(
        content=text or None,
        tool_calls=tool_calls,
        provider_specific_fields={
            "citations": citations, 
            "thinking_blocks": thinking_blocks,
            **blocks_provider_specific_fields
        },
        thinking_blocks=thinking_blocks,
        reasoning_content=reasoning,
    )
    mr.choices[0].finish_reason = map_finish_reason(completion_response.get("stop_reason"))
    mr.model = completion_response.get("model", default_model)
    mr.created = int(time.time())

    mr.usage = cfg.calculate_usage(usage_object=completion_response.get("usage", {}) or {}, reasoning_content=reasoning)  # type: ignore

    mr._hidden_params = {"original_response": completion_response.get("content")}
    return mr

