# gophian -- tools to help with Debianizing Go software
# Copyright (C) 2024-2025 Maytham Alsudany <maytha8thedev@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from importlib.util import find_spec

import click
from requests.adapters import HTTPAdapter
from requests_cache import CachedSession
from urllib3.util.retry import Retry

from gophian.__about__ import VERSION, COPYRIGHT_NOTICE
from gophian.cli.create_salsa_repo import create_salsa_repo
from gophian.cli.estimate import estimate
from gophian.cli.make import make
from gophian.cli.search import search
from gophian.cli.show import show
from gophian.cli.license_text import license_text


def print_version(ctx: click.Context, _, value: bool) -> None:
    if not value or ctx.resilient_parsing:
        return
    click.echo(VERSION)
    ctx.exit()


def print_copyright(ctx: click.Context, _, value: bool) -> None:
    if not value or ctx.resilient_parsing:
        return
    click.echo(COPYRIGHT_NOTICE)
    ctx.exit()


@click.group()
@click.option(
    "--version",
    is_flag=True,
    callback=print_version,
    expose_value=False,
    is_eager=True,
    help="Print version and exit.",
)
@click.option(
    "--copyright",
    is_flag=True,
    callback=print_copyright,
    expose_value=False,
    is_eager=True,
    help="Print copyright notice and exit.",
)
@click.pass_context
def cli(ctx: click.Context) -> None:
    """
    Tools to help with Debianizing Go software.
    """
    session = CachedSession(
        "gophian",
        backend="sqlite",
        expire_after=60 * 60,
        use_cache_dir=True,
        allowable_methods=["HEAD", "GET"],
    )
    retries = Retry(
        total=5,
        backoff_factor=0.1,
        status_forcelist=[502, 503, 504],
        allowed_methods={"GET", "HEAD", "POST"},
    )
    session.mount("https://", HTTPAdapter(max_retries=retries))
    ctx.obj = session


cli.add_command(estimate)
cli.add_command(make)
cli.add_command(create_salsa_repo)
cli.add_command(search)
cli.add_command(show)
cli.add_command(license_text)


if find_spec("graphviz"):
    from gophian.cli.estimate_graphviz import estimate_graphviz

    cli.add_command(estimate_graphviz)
