# matrix-appservice-kakaotalk - A Matrix-KakaoTalk puppeting bridge.
# Copyright (C) 2022 Tulir Asokan, Andrew Ferrazzutti
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
from __future__ import annotations

from typing import Match
import re

from mautrix.types import Format, MessageType, TextMessageEventContent

from ..kt.types.chat.attachment.mention import MentionStruct

from .. import puppet as pu, user as u


MENTION_REGEX = re.compile(r"@(\d+)\u2063(.+?)\u2063")


async def kakaotalk_to_matrix(msg: str | None, mentions: list[MentionStruct] | None) -> TextMessageEventContent:
    # TODO Shouts
    text = msg or ""
    content = TextMessageEventContent(msgtype=MessageType.TEXT, body=text)

    if mentions:
        mention_user_ids = []
        at_chunks = text.split("@")
        for m in mentions:
            for idx in m.at:
                chunk = at_chunks[idx]
                original = chunk[:m.len]
                mention_user_ids.append(int(m.user_id))
                at_chunks[idx] = f"{m.user_id}\u2063{original}\u2063{chunk[m.len:]}"
        text = "@".join(at_chunks)

        mention_user_map = {}
        for ktid in mention_user_ids:
            user = await u.User.get_by_ktid(ktid)
            if user:
                mention_user_map[ktid] = user.mxid
            else:
                puppet = await pu.Puppet.get_by_ktid(ktid, create=False)
                mention_user_map[ktid] = puppet.mxid if puppet else None

        if mention_user_map:
            def _mention_replacer(match: Match) -> str:
                mxid = mention_user_map[int(match.group(1))]
                if not mxid:
                    return match.group(2)
                return f'<a href="https://matrix.to/#/{mxid}">{match.group(2)}</a>'

            content.format = Format.HTML
            content.formatted_body = MENTION_REGEX.sub(_mention_replacer, text).replace("\n", "<br/>\n")
    return content