#!/usr/bin/env python3
#
# Copyright (c) 2024 YunoHost Contributors
#
# This file is part of YunoHost (see https://yunohost.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 argparse

import yunohost

# Default server configuration
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 6787


def _parse_api_args() -> argparse.Namespace:
    """Parse main arguments for the api"""
    parser = argparse.ArgumentParser(
        add_help=False,
        description="Run the YunoHost API to manage your server.",
    )
    srv_group = parser.add_argument_group("server configuration")
    srv_group.add_argument(
        "-h",
        "--host",
        action="store",
        default=DEFAULT_HOST,
        help=f"Host to listen on (default: {DEFAULT_HOST})",
    )
    srv_group.add_argument(
        "-p",
        "--port",
        action="store",
        default=DEFAULT_PORT,
        type=int,
        help=f"Port to listen on (default: {DEFAULT_PORT})",
    )
    srv_group.add_argument(
        "--actionsmap",
        action="store",
        default=None,
        type=str,
        help="Alternate actionsmap to use for moulinette; useful for development",
    )
    glob_group = parser.add_argument_group("global arguments")
    glob_group.add_argument(
        "--debug",
        action="store_true",
        default=False,
        help="Set log level to DEBUG",
    )
    glob_group.add_argument(
        "--help",
        action="help",
        help="Show this help message and exit",
    )

    return parser.parse_args()


if __name__ == "__main__":
    opts = _parse_api_args()
    # Run the server
    yunohost.api(
        debug=opts.debug, host=opts.host, port=opts.port, actionsmap=opts.actionsmap
    )
