#!/usr/bin/env python3

# Libervia plugin
# Copyright (C) 2009-2025 Jérôme Poisson (goffi@goffi.org)

# 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 <http://www.gnu.org/licenses/>.

import base64
from typing import Final, TYPE_CHECKING, cast

from twisted.words.protocols.jabber import jid
from twisted.words.protocols.jabber.xmlstream import XMPPHandler
from twisted.words.xish import domish
from wokkel import data_form, disco, iwokkel
from zope.interface import implementer

from libervia.backend.core import exceptions
from libervia.backend.core.constants import Const as C
from libervia.backend.core.core_types import SatXMPPEntity
from libervia.backend.core.i18n import _
from libervia.backend.core.log import getLogger
from libervia.backend.plugins import plugin_xep_0373
from .plugin_exp_gre import Encrypter

if TYPE_CHECKING:
    from libervia.backend.core.main import LiberviaBackend

log = getLogger(__name__)


PLUGIN_INFO = {
    C.PI_NAME: "GRE Encrypter: OpenPGP",
    C.PI_IMPORT_NAME: "GRE-OpenPGP",
    C.PI_TYPE: "XEP",
    C.PI_MODES: C.PLUG_MODE_BOTH,
    C.PI_PROTOCOLS: [],
    C.PI_DEPENDENCIES: [
        "GRE",
    ],
    C.PI_RECOMMENDATIONS: [],
    C.PI_MAIN: "GREEncrypterOpenPGP",
    C.PI_HANDLER: "yes",
    C.PI_DESCRIPTION: _("Handle MIME formatting for Gateway Relayed Encryption."),
}

NS_GRE_OPENPGP: Final = "urn:xmpp:gre:encrypter:openpgp:0"


class GREEncrypterOpenPGP(Encrypter):
    name = "openpgp"
    namespace = NS_GRE_OPENPGP

    def __init__(self, host: "LiberviaBackend") -> None:
        log.info(f"plugin {PLUGIN_INFO[C.PI_NAME]!r} initialization")
        super().__init__(host)
        host.register_namespace("gre-openpgp", NS_GRE_OPENPGP)

    def get_handler(self, client: SatXMPPEntity) -> XMPPHandler:
        return GREMIMEHandler(self)

    async def encrypt(
        self,
        client: SatXMPPEntity,
        recipient_id: str,
        message_elt: domish.Element,
        formatted_payload: bytes,
        encryption_data_form: data_form.Form,
    ) -> str:
        gpg_provider = plugin_xep_0373.get_gpg_provider(self.host, client)
        public_keys = gpg_provider.list_public_keys(recipient_id)
        if not public_keys:
            raise exceptions.NotFound(
                f"No public keys found for {recipient_id!r}, we can't encrypt."
            )
        encrypted_data = gpg_provider.encrypt(
            formatted_payload, public_keys
        )
        return base64.b64encode(encrypted_data).decode("ASCII")


@implementer(iwokkel.IDisco)
class GREMIMEHandler(XMPPHandler):

    def __init__(self, plugin_parent):
        self.plugin_parent = plugin_parent

    def getDiscoInfo(
        self, requestor: jid.JID, target: jid.JID, nodeIdentifier: str = ""
    ) -> list[disco.DiscoFeature]:
        return [
            disco.DiscoFeature(NS_GRE_OPENPGP),
        ]

    def getDiscoItems(
        self, requestor: jid.JID, target: jid.JID, nodeIdentifier: str = ""
    ) -> list[disco.DiscoItems]:
        return []
