# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2026, Chris Caron <lead2gold@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from itertools import chain
from json import loads
import re

import requests

from ..common import NotifyType, PersistentStoreMode
from ..exception import AppriseException
from ..locale import gettext_lazy as _
from ..url import PrivacyMode
from ..utils.parse import parse_list
from .base import NotifyBase

# Is Group Detection
IS_GROUP = re.compile(
    r"^\s*((#|%23)(?P<group>[a-z0-9_-]+)|"
    r"((#|%23)?(?P<all>all|everyone|\*)))\s*$",
    re.I,
)

# Is User Detection
IS_USER = re.compile(
    r"^\s*(@|%40)?(?P<user>[a-z0-9_-]+)\s*$",
    re.I,
)


class NextcloudGroupDiscoveryException(AppriseException):
    """Apprise Nextcloud Group Discovery Exception Class."""


class NotifyNextcloud(NotifyBase):
    """A wrapper for Nextcloud Notifications.

    Targets can be individual users, groups, or everyone:
    - user: specify one or more usernames as path segments
    - group: prefix with a hash (e.g., ``#DevTeam``)
    - everyone: use ``all`` (aliases: ``everyone``, ``*``)

    Group and everyone expansion uses Nextcloud's OCS provisioning API and
    requires appropriate permissions (typically an admin account) and the
    provisioning API enabled on the server.
    """

    # The default descriptive name associated with the Notification
    service_name = "Nextcloud"

    # The services URL
    service_url = "https://nextcloud.com/"

    # Insecure protocol (for those self hosted requests)
    protocol = "ncloud"

    # The default protocol (this is secure for notica)
    secure_protocol = "nclouds"

    # A URL that takes you to the setup/help of the specific protocol
    setup_url = "https://appriseit.com/services/nextcloud/"

    # Nextcloud title length
    title_maxlen = 255

    # Defines the maximum allowable characters per message.
    body_maxlen = 4000

    # Our default is to not use persistent storage beyond in-memory
    # reference
    storage_mode = PersistentStoreMode.AUTO

    # Defines how long we cache our discovery for
    group_discovery_cache_length_sec = 86400

    # unique identifier to cache the 'all' group category
    all_group_id = "all"

    # Define object templates
    templates = (
        "{schema}://{host}/{targets}",
        "{schema}://{host}:{port}/{targets}",
        "{schema}://{user}:{password}@{host}/{targets}",
        "{schema}://{user}:{password}@{host}:{port}/{targets}",
    )

    # Define our template tokens
    template_tokens = dict(
        NotifyBase.template_tokens,
        **{
            "host": {
                "name": _("Hostname"),
                "type": "string",
                "required": True,
            },
            "port": {
                "name": _("Port"),
                "type": "int",
                "min": 1,
                "max": 65535,
            },
            "user": {
                "name": _("Username"),
                "type": "string",
            },
            "password": {
                "name": _("Password"),
                "type": "string",
                "private": True,
            },
            "target_user": {
                "name": _("Target User"),
                "type": "string",
                "map_to": "targets",
                "prefix": "@",
            },
            "target_group": {
                "name": _("Target Group"),
                "type": "string",
                "map_to": "targets",
                "prefix": "#",
            },
            "targets": {
                "name": _("Targets"),
                "type": "list:string",
                "required": True,
            },
        },
    )

    # Define our template arguments
    template_args = dict(
        NotifyBase.template_args,
        **{
            # Nextcloud uses different API end points depending on the version
            # being used however the (API) payload remains the same.  Allow
            # users to specify the version they are using:
            "version": {
                "name": _("Version"),
                "type": "int",
                "min": 1,
                "default": 21,
            },
            "url_prefix": {
                "name": _("URL Prefix"),
                "type": "string",
            },
            "to": {
                "alias_of": "targets",
            },
        },
    )

    # Define any kwargs we're using
    template_kwargs = {
        "headers": {
            "name": _("HTTP Header"),
            "prefix": "+",
        },
    }

    def __init__(
        self,
        targets=None,
        version=None,
        headers=None,
        url_prefix=None,
        **kwargs,
    ):
        """Initialize Nextcloud Object."""
        super().__init__(**kwargs)

        # Store our targets
        self.targets = []
        self.groups = set()

        for target in parse_list(targets):
            results = IS_GROUP.match(target)
            if results:
                group_id = (
                    self.all_group_id
                    if results.group("all")
                    else results.group("group")
                )

                self.groups.add(group_id)
                self.logger.debug("Added Nextcloud group '%s'", group_id)
                continue

            results = IS_USER.match(target)
            if results:
                # Store our target
                self.targets.append(results.group("user"))
                self.logger.debug(
                    "Added Nextcloud user '%s'", self.targets[-1]
                )
                continue

            self.logger.warning(
                "Ignored invalid Nextcloud user/group '%s'", target
            )

        self.version = self.template_args["version"]["default"]
        if version is not None:
            try:
                self.version = int(version)
                if self.version < self.template_args["version"]["min"]:
                    # Let upper exception handle this
                    raise ValueError()

            except (ValueError, TypeError):
                msg = (
                    f"At invalid Nextcloud version ({version}) was specified."
                )
                self.logger.warning(msg)
                raise TypeError(msg) from None

        # Support URL Prefix
        self.url_prefix = (
            "" if not url_prefix else ("/" + url_prefix.strip("/"))
        )

        self.headers = {}
        if headers:
            # Store our extra headers
            self.headers.update(headers)

        return

    def _fetch(self, payload=None, target=None, group=None):
        """Wrapper to NextCloud API requests object."""

        # our method
        method = "POST" if target else "GET"

        # Prepare our Header
        headers = {
            "User-Agent": self.app_id,
            "OCS-APIREQUEST": "true",
            "Accept": "application/json",
        }

        # Apply any/all header over-rides defined
        headers.update(self.headers)

        # Prepare base URL fragments
        scheme = "https" if self.secure else "http"
        host_port = (
            self.host
            if not isinstance(self.port, int)
            else f"{self.host}:{self.port}"
        )
        base = f"{scheme}://{host_port}"
        if self.url_prefix:
            base = f"{base}{self.url_prefix}"

        # Auth
        auth = (self.user, self.password) if self.user else None

        # our URL Parameters
        params = {}

        # our response
        content = None

        if target:
            # Nextcloud URL based on version used
            query = f'v{self.version} Notify "{target}"'
            esc_target = NotifyNextcloud.quote(target)
            url = (
                f"{base}/ocs/v2.php/"
                "apps/admin_notifications/"
                f"api/v1/notifications/{esc_target}"
                if self.version < 21
                else (
                    f"{base}/ocs/v2.php/"
                    "apps/notifications/"
                    f"api/v2/admin_notifications/{esc_target}"
                )
            )

        elif group:
            query = f'Group "{group}"'
            params = {
                "format": "json",
            }
            esc_group = NotifyNextcloud.quote(group)
            url = f"{base}/ocs/v1.php/cloud/groups/{esc_group}"

        else:  # Users
            query = "Users"
            params = {
                "format": "json",
            }
            url = f"{base}/ocs/v1.php/cloud/users"

        self.throttle()
        self.logger.debug(
            "Nextcloud %s %s URL: %s (cert_verify=%r)",
            query,
            method,
            url,
            self.verify_certificate,
        )

        if payload:
            self.logger.debug(
                "Nextcloud v%d Payload: %s", self.version, payload
            )

        try:
            # Prepare our request object
            request = requests.post if target else requests.get

            r = request(
                url,
                headers=headers,
                data=payload,
                params=params,
                auth=auth,
                verify=self.verify_certificate,
                timeout=self.request_timeout,
            )

            try:
                content = loads(r.content)

            except (AttributeError, TypeError, ValueError):
                # ValueError = r.content is Unparsable
                # TypeError = r.content is None
                # AttributeError = r is None
                content = {}

            if r.status_code != requests.codes.ok:
                status_str = NotifyNextcloud.http_response_code_lookup(
                    r.status_code
                )

                self.logger.warning(
                    "Failed to send Nextcloud %s: %s%serror=%d.",
                    query,
                    status_str,
                    ", " if status_str else "",
                    r.status_code,
                )

                self.logger.debug(
                    "Response Details:\r\n%r", (r.content or b"")[:2000]
                )

                if target:
                    return (False, content)

                raise NextcloudGroupDiscoveryException(
                    f"{query} non-200 response"
                )

        except requests.RequestException as e:
            self.logger.warning(
                "A Connection error occurred with Nextcloud %s",
                query,
            )
            self.logger.debug(f"Socket Exception: {e!s}")

            if target:
                return (False, None)
            raise NextcloudGroupDiscoveryException(
                f"{query} socket exception"
            ) from None

        self.logger.info("Sent Nextcloud %s", query)
        return (True, content)

    def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs):
        """Perform Nextcloud Notification."""

        # Create a copy of our targets
        targets = set(self.targets)

        # Initialize our has_error flag
        has_error = False

        if self.groups:
            # Append our group lookup
            try:
                for group in self.groups:
                    if group == self.all_group_id:
                        targets |= self.all_users()

                    else:
                        # specific group
                        targets |= self.users_by_group(group)

            except NextcloudGroupDiscoveryException:
                # logging already handled within all_users and user_by_group()
                return False

        if not targets:
            # There were no services to notify
            self.logger.warning("There were no Nextcloud targets to notify.")
            return False

        for target in targets:
            # Prepare our Payload
            payload = {
                "shortMessage": title if title else self.app_desc,
            }
            if body:
                # Only store the longMessage if a body was defined; nextcloud
                # doesn't take kindly to empty longMessage entries.
                payload["longMessage"] = body

            is_okay, _ = self._fetch(payload, target)
            if not is_okay:
                # Toggle our status
                has_error = True

        return not has_error

    def users_by_group(self, group):
        """
        Lists users associated with a provided group
        """

        # Check our cache
        targets = self.store.get(group)
        if targets is not None:
            # Returned cached value
            self.logger.trace(
                f"Using Nextcloud cached response for group '{group}' query"
            )
            return set(targets)

        # _fetch throws an exception if it fails, so we can
        # go ahead and ignore checking for it.
        _, response = self._fetch(group=group)

        # Initialize our targets
        targets = set()

        # If we get here, our fetch was successful; look up our users
        users = response.get("ocs", {}).get("data", {}).get("users")
        if isinstance(users, list):
            targets = {s for u in users if (s := str(u).strip())}

        if not targets:
            self.logger.warning(
                "No users associated with Nextcloud group '%s'", group
            )

        self.store.set(
            group, list(targets), expires=self.group_discovery_cache_length_sec
        )
        return targets

    def all_users(self):
        """
        Lists users associated with Nextcloud instance
        """
        # Check our cache
        targets = self.store.get(self.all_group_id)
        if targets is not None:
            self.logger.trace(
                "Using Nextcloud cached response for all-user query"
            )
            return set(targets)

        # _fetch throws an exception if it fails, so we can
        # go ahead and ignore checking for it.
        _, response = self._fetch()

        # Initialize our targets
        targets = set()

        # If we get here, our fetch was successful; look up our users
        users = response.get("ocs", {}).get("data", {}).get("users")
        if isinstance(users, list):
            targets = {s for u in users if (s := str(u).strip())}

        if not targets:
            self.logger.warning(
                "Failed to retrieve all users from Nextcloud",
            )
            # early exit; no cache
            return targets

        self.store.set(
            self.all_group_id,
            list(targets),
            expires=self.group_discovery_cache_length_sec,
        )
        return targets

    @property
    def url_identifier(self):
        """Returns all of the identifiers that make this URL unique from
        another simliar one.

        Targets or end points should never be identified here.
        """
        return (
            self.secure_protocol if self.secure else self.protocol,
            self.user,
            self.password,
            self.host,
            self.port,
            self.url_prefix,
        )

    def url(self, privacy=False, *args, **kwargs):
        """Returns the URL built dynamically based on specified arguments."""

        # Create URL parameters from our headers
        params = {f"+{k}": v for k, v in self.headers.items()}

        # Set our version
        params["version"] = str(self.version)

        if self.url_prefix.rstrip("/"):
            params["url_prefix"] = self.url_prefix

        # Extend our parameters
        params.update(self.url_parameters(privacy=privacy, *args, **kwargs))

        # Determine Authentication
        auth = ""
        if self.user and self.password:
            auth = "{user}:{password}@".format(
                user=NotifyNextcloud.quote(self.user, safe=""),
                password=self.pprint(
                    self.password, privacy, mode=PrivacyMode.Secret, safe=""
                ),
            )
        elif self.user:
            auth = "{user}@".format(
                user=NotifyNextcloud.quote(self.user, safe=""),
            )

        group_prefix = self.template_tokens["target_group"]["prefix"]
        user_prefix = self.template_tokens["target_user"]["prefix"]

        default_port = 443 if self.secure else 80
        return "{schema}://{auth}{hostname}{port}/{targets}?{params}".format(
            schema=self.secure_protocol if self.secure else self.protocol,
            auth=auth,
            # never encode hostname since we're expecting it to be a
            # valid one
            hostname=self.host,
            port=(
                ""
                if self.port is None or self.port == default_port
                else f":{self.port}"
            ),
            targets="/".join(
                [
                    NotifyNextcloud.quote(x, safe=(group_prefix + user_prefix))
                    for x in chain(
                        # Groups are prefixed with a pound/hashtag symbol
                        [f"{group_prefix}{x}" for x in self.groups],
                        # Users
                        [f"{user_prefix}{x}" for x in self.targets],
                    )
                ]
            ),
            params=NotifyNextcloud.urlencode(params),
        )

    def __len__(self):
        """Returns the number of targets associated with this notification."""
        targets = len(self.targets) + len(self.groups)
        return max(1, targets)

    @staticmethod
    def parse_url(url):
        """Parses the URL and returns enough arguments that can allow us to re-
        instantiate this object."""

        results = NotifyBase.parse_url(url)
        if not results:
            # We're done early as we couldn't load the results
            return results

        # Fetch our targets
        results["targets"] = NotifyNextcloud.split_path(results["fullpath"])

        # The 'to' makes it easier to use yaml configuration
        if "to" in results["qsd"] and len(results["qsd"]["to"]):
            results["targets"] += NotifyNextcloud.parse_list(
                results["qsd"]["to"]
            )

        # Allow users to over-ride the Nextcloud version being used
        if "version" in results["qsd"] and len(results["qsd"]["version"]):
            results["version"] = NotifyNextcloud.unquote(
                results["qsd"]["version"]
            )

        # Support URL Prefixes
        if "url_prefix" in results["qsd"] and len(
            results["qsd"]["url_prefix"]
        ):
            results["url_prefix"] = NotifyNextcloud.unquote(
                results["qsd"]["url_prefix"]
            )

        # Add our headers that the user can potentially over-ride if they wish
        # to to our returned result set and tidy entries by unquoting them
        results["headers"] = {
            NotifyNextcloud.unquote(x): NotifyNextcloud.unquote(y)
            for x, y in results["qsd+"].items()
        }

        return results
