import logging
from dataclasses import dataclass
from typing import Optional

import bleach
import markdown
from django import forms
from django.db import models
from django.urls import reverse
from scrobbles.dataclasses import BaseLogData
from scrobbles.mixins import ScrobblableConstants, ScrobblableMixin

logger = logging.getLogger(__name__)
BNULL = {"blank": True, "null": True}

AGENT_HTML_ALLOWED_TAGS = [
    "p",
    "br",
    "strong",
    "em",
    "a",
    "ul",
    "ol",
    "li",
    "code",
    "pre",
    "blockquote",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "hr",
    "img",
    "table",
    "thead",
    "tbody",
    "tr",
    "th",
    "td",
]


@dataclass
class AgentSessionLogData(BaseLogData):
    title: Optional[str] = None
    provider: Optional[str] = None
    model: Optional[str] = None
    turns: Optional[list] = None

    _excluded_fields = {"turns"}

    @classmethod
    def override_fields(cls) -> dict:
        return {
            "title": forms.CharField(required=False),
            "provider": forms.CharField(required=False),
            "model": forms.CharField(required=False),
        }

    @property
    def pending(self) -> bool:
        if not self.turns:
            return False
        return any(turn.get("response") is None for turn in self.turns)

    @staticmethod
    def _md_to_html(text: str) -> str:
        md = markdown.Markdown(extensions=["extra"])
        return bleach.clean(md.convert(text), tags=AGENT_HTML_ALLOWED_TAGS, strip=True)

    def as_html(self) -> str:
        if not self.turns:
            return ""

        html_parts = []
        for i, turn in enumerate(self.turns):
            prompt = turn.get("prompt", "")
            response = turn.get("response")
            html_parts.append('<div class="agent-turn">')
            html_parts.append(
                f'<div class="agent-prompt"><h5>Prompt {i + 1}</h5>'
                f"{self._md_to_html(prompt)}</div>"
            )
            if response:
                html_parts.append(
                    f'<div class="agent-response"><h5>Response</h5>'
                    f"{self._md_to_html(response)}</div>"
                )
            else:
                html_parts.append(
                    '<div class="agent-response agent-thinking">Thinking&hellip;</div>'
                )
            html_parts.append("</div>")
        return "".join(html_parts)


class AgentSession(ScrobblableMixin):
    provider = models.CharField(max_length=50, **BNULL)
    model = models.CharField(max_length=100, **BNULL)

    @classmethod
    def find_or_create(cls, provider: str, model: str):
        agent_session = cls.objects.filter(provider=provider, model=model).first()
        if agent_session:
            return agent_session, False
        title = f"{provider} {model}".strip()
        agent_session = cls.objects.create(provider=provider, model=model, title=title)
        return agent_session, True

    def __str__(self):
        if self.title:
            return self.title
        return str(self.uuid)

    def get_absolute_url(self):
        return reverse("agents:agent_session_detail", kwargs={"slug": self.uuid})

    @property
    def subtitle(self) -> str:
        return " ".join(p for p in [self.provider, self.model] if p)

    @property
    def strings(self) -> ScrobblableConstants:
        return ScrobblableConstants(verb="Asking", tags="agents")

    @property
    def start_url(self) -> str:
        return ""

    @property
    def logdata_cls(self):
        return AgentSessionLogData

    @property
    def primary_image_url(self) -> str:
        return ""
