# 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 pathlib import Path
from typing import Optional

import click
import requests


@click.command()
@click.argument("project", required=False)
@click.pass_context
def create_salsa_repo(context: click.Context, project: Optional[str]) -> None:
    """
    Create a Salsa repo within the Debian Go Package Team.

    If no project name is passed, this checks if the 'Source' field has been
    defined in a debian/control file, and uses that instead.
    """

    session: requests.Session = context.obj

    if project is not None:
        repo = project
    elif name := package_name_from_control():
        repo = name
    else:
        click.secho(
            "No project argument passed, and no debian/control file found with source package defined.",
            fg="red",
        )
        context.exit(1)

    if "/" in repo:
        click.secho("Repo name must not contain slashes.", fg="red")
        context.exit(1)

    res = session.post(
        "https://pgt-api-server.debian.net/v1/createrepo", params={"repo": repo}
    )

    if res.status_code == 200:
        click.secho(
            "Repo created successfully at https://salsa.debian.org/go-team/packages/"
            + repo,
            fg="green",
            bold=True,
        )
    elif res.status_code == 403:
        click.secho(
            "Repository creation has been disabled; please see the mailing list (debian-go@lists.debian.org)",
            fg="red",
        )
    else:
        click.secho(
            f"An unknown problem occurred; status code {res.status_code} recieved.",
            fg="red",
        )


def package_name_from_control() -> Optional[str]:
    control = Path("debian/control")
    if control.exists():
        with control.open("r") as file:
            line = next(file)
            if line.startswith("Source:"):
                return line[7:].strip()
            else:
                return None
    else:
        return None
