import base64
from typing import TYPE_CHECKING, Any

import rt.rest2
from rt.rest2 import Attachment

from csirtmu.self_service_backend.config import RTConfig
from csirtmu.self_service_backend.input_structs import FormData, RTFormattedData

if TYPE_CHECKING:
    from collections.abc import Iterator


class RTClient:
    def __init__(self, rt_config: RTConfig) -> None:
        self.rt = rt.rest2.Rt(url=rt_config.host, token=rt_config.token, verify_cert=rt_config.verify_cert)

    def create_ticket_from_form_data(self, data: FormData, requestor: str, subject: str) -> int:
        formatted = self._format_data(data)
        return self.rt.create_ticket(
            "General",
            "text/plain",
            content=formatted.content,
            attachments=formatted.attachments,
            Requestor=requestor,
            Subject=subject,
        )

    def get_user_tickets(self, user: str) -> list[dict[str, Any]]:
        tickets: Iterator[dict[str, Any]] = self.rt.search(Requestors__like=user)
        return [ticket | {"url": f"{self.rt.base_url}Ticket/Display.html?id={ticket['id']}"} for ticket in tickets]

    def _format_data(self, data: FormData) -> RTFormattedData:
        res = RTFormattedData("", [])
        for attachment in data.attachments:
            res.attachments.append(
                Attachment(
                    file_name=attachment.name,
                    file_content=base64.b64decode(attachment.content),
                    file_type=attachment.type,
                )
            )
        for name, value in data.fields.items():
            res.content += f"{name}: {value}\n"
        return res
