import os
from typing import Optional, List, Dict
from blocks_control_sdk.clients.api import Chat, BlocksMessageCreate
from blocks_control_sdk.tools.slack_utils import markdown_to_slack_blocks
from blocks_control_sdk.utils import patch_blocks_runtime_config, BlocksRuntimeConfigKeys

BLOCKS_CHAT_ID = os.getenv("BLOCKS_CHAT_ID")
BLOCKS_ENV = os.getenv("BLOCKS_ENV")
BLOCKS_WORKSPACE_ID = os.getenv("BLOCKS_WORKSPACE_ID")
THRESHOLD_URGENCY_LEVEL = int(os.getenv("THRESHOLD_URGENCY_LEVEL", "0"))

def _get_session_url() -> str:
    if BLOCKS_ENV == "prod":
        return f"https://blocksorg.com/app/{BLOCKS_WORKSPACE_ID}/sessions/{BLOCKS_CHAT_ID}"
    return f"https://app{BLOCKS_ENV}.blocksorg.com/app/{BLOCKS_WORKSPACE_ID}/sessions/{BLOCKS_CHAT_ID}"

def _get_dashboard_button_block() -> dict:
    return {
        "type": "actions",
        "elements": [
            {
                "type": "button",
                "text": {
                    "type": "plain_text",
                    "text": "View on dashboard"
                },
                "url": _get_session_url(),
                "style": "primary"
            }
        ]
    }

def to_slack_blocks_with_dashboard_button(message: str) -> List[Dict]:
    """Convert markdown message to Slack blocks and append a dashboard button."""
    _, message_blocks = markdown_to_slack_blocks(message)
    message_blocks.append(_get_dashboard_button_block())
    return message_blocks

def get_task_message_with_footer(message: str, is_github: bool = False) -> str:
    session_url = _get_session_url()

    if is_github:
        return f"""{message}

**[View on dashboard]({session_url})**"""
    else:
        return f"""{message}
---
[view on dashboard]({session_url})."""

def get_task_header(is_github: bool = False) -> str:
    session_url = _get_session_url()
    markdown = "I'm working on this request and will respond here shortly."

    if is_github:
        return f"""{markdown}

**[View on dashboard]({session_url})**"""
    else:
        return markdown

def todo_list_update__blocks(body: str) -> str:
    # update the comment body with the new todo list
    print("="*100)
    print(f"ACTION: todo_list_update__blocks")
    print("="*100)

    chatapi = Chat()
    chatapi.create_message(BlocksMessageCreate(
        message=body,
        role="assistant",
        type="todo"
    ))

    patch_blocks_runtime_config({
       BlocksRuntimeConfigKeys.LATEST_TODO_LIST: body
    })

    return f"Updated todo list in Blocks."


def send_message__blocks(
    message: str, 
    urgency_level_between_zero_to_10: int = 5, 
    role: str = "assistant", 
    type: str = "message", 
    chat_thread_id: str = None,
    artifact_id: Optional[str] = None,
    artifact_metadata: Optional[dict] = None
) -> str:
    print("="*100)
    print(f"ACTION: Sending message to user: {message}")
    print(f"ACTION: Role: {role}")
    print(f"ACTION: Type: {type}")
    print(f"ACTION: Chat thread id: {chat_thread_id}")
    print(f"ACTION: Urgency level: {urgency_level_between_zero_to_10}")
    print("="*100)

    # if urgency_level_between_zero_to_10 < THRESHOLD_URGENCY_LEVEL:
    #     return f"This message is not urgent enough to send to the user. Attempt to continue with the task without user input."

    chatapi = Chat()
    chatapi.create_message(BlocksMessageCreate(
        message=message,
        role=role,
        type=type,
        chat_thread_id=chat_thread_id,
        artifact_id=artifact_id,
        artifact_metadata=artifact_metadata
    ))

    return f"Sent message to user."
