# -*- coding: utf-8 -*-
# SPDX-License-Identifier: GPL-2+
# Copyright 2023 Helmut Grohne

import re

import dput.command
import dput.commands.dm
import dput.exceptions


class MigrateException(dput.exceptions.DcutError):
    pass


class MigrateCommand(dput.command.AbstractCommand):
    def __init__(self, interface):
        super().__init__(interface)
        self.cmd_name = "migrate"
        self.cmd_purpose = "migrate or block a staged upload"

    def name_and_purpose(self):
        return (self.cmd_name, self.cmd_purpose)

    def register(self, parser, **kwargs):
        parser.add_argument(
            "--reject",
            default=False,
            action="store_true",
            help="reject the upload rather than accepting it",
        )
        parser.add_argument(
            "source",
            action="store",
            help="source package to operate on",
        )
        parser.add_argument(
            "version",
            action="store",
            help="source version to operate on",
        )

    def validate(self, args):
        if not re.match("^[a-z0-9][a-z0-9.+-]+$", args.source):
            raise MigrateException("invalid source package name")
        if not re.match("^[A-Za-z0-9.+:~-]+$", args.version):
            raise MigrateException("invalid source version")

    def generate_commands_name(self, profile):
        return dput.commands.dm.generate_dak_commands_name(profile)

    def produce(self, fh, args):
        command = "REJECT" if args.reject else "ACCEPT"
        # The initial empty line is important.
        fh.write(f"""
Action: process-upload
Command: {command}
Source: {args.source}
Version: {args.version}
""")
