from __future__ import annotations

from ...options.gen_agent_messages import GenAgentBizParamOptions, GenAgentReqOptions
from .._schemas.genagent.gen_agent_messages import (
    Attachment,
    BizParam,
    Message,
    Metadata,
    MultiPart,
    SendMessageGenAgentBody,
)
from .._schemas.genagent.gen_agent_messages import (
    Content as MessageContent,
)


def build_stream_gen_agent_message(
    *,
    conv_id: str,
    message: str,
    start_new_topic: bool,
    role: str,
    parent_msg_id: str | None = None,
    options: GenAgentReqOptions | None = None,
) -> SendMessageGenAgentBody:
    opt = options.model_copy(deep=True) if options else GenAgentReqOptions()

    multi_parts = [
        MultiPart(
            content_type="image",
            url=img.url,
            width=img.width,
            height=img.height,
        )
        for img in opt.images
    ]

    if message:
        multi_parts.append(MultiPart(content_type="text", text=message))

    metadata: Metadata | None = None
    if opt.images:
        metadata = Metadata(
            attachments=[
                Attachment(
                    content_type="image",
                    url=img.url,
                    width=img.width,
                    height=img.height,
                )
                for img in opt.images
            ]
        )

    has_images = bool(opt.images)

    biz_param: BizParam | None = None
    if opt.biz_param is not None or has_images:
        opt.biz_param = (
            GenAgentBizParamOptions() if opt.biz_param is None else opt.biz_param
        )
        biz_param = BizParam(
            curr_base_model_name=opt.biz_param.curr_base_model_name,
            curr_model_id=opt.biz_param.curr_model_id,
            curr_model_ver_id=opt.biz_param.curr_model_ver_id,
            conv_type=opt.biz_param.conv_type,
            current_workspace_type=opt.biz_param.current_workspace_type,
            video_base_model_name=opt.biz_param.video_base_model_name,
            video_model_id=opt.biz_param.video_model_id,
            video_model_ver_id=opt.biz_param.video_model_ver_id,
        )

    enable_agent: bool | None
    if has_images:
        content = MessageContent(multi_parts=multi_parts)
        enable_agent = True
    else:
        content = MessageContent(content_type="text", parts=[message])
        enable_agent = opt.enable_agent

    return SendMessageGenAgentBody(
        conv_id=conv_id,
        seg_id=opt.seg_id or "",
        version=opt.version,
        enable_agent=enable_agent,
        start_new_topic=start_new_topic,
        messages=[
            Message(
                role=role,
                content=content,
                metadata=metadata,
            )
        ],
        biz_param=biz_param,
        safe_scene=opt.safe_scene,
        select_agent_mode=opt.select_agent_mode,
        parent_msg_id=parent_msg_id,
        is_first_msg=not bool(parent_msg_id),
    )
