# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Migrate existing Workflow Templates to use runtime_parameters."""

from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps

from debusine.client.models import RuntimeParameter

# This migration needs a snapshot of the available parameters for each
# workflow at the relevant point in Debusine's history, and Django's normal
# migration system doesn't keep track of that information.  The following is
# the result of checking out 51b9140e41d6a4677e349c4be6eed0ab06b4bbd6 (when
# this migration initially landed on devel) and running:
#
#   from debusine.artifacts.models import TaskTypes
#   from debusine.tasks import BaseTask
#
#   print(
#       {
#           task_name: sorted(workflow_cls.task_data_type.__fields__)
#           for task_name, workflow_cls in BaseTask._sub_tasks[
#               TaskTypes.WORKFLOW
#           ].items()
#       }
#   )

workflow_parameters = {
    "autopkgtest": [
        "arch_all_build_architecture",
        "architectures",
        "backend",
        "binary_artifacts",
        "codename",
        "context_artifacts",
        "debug_level",
        "enable_regression_tracking",
        "exclude_tests",
        "extra_environment",
        "extra_repositories",
        "fail_on",
        "include_tests",
        "needs_internet",
        "prefix",
        "qa_suite",
        "reference_prefix",
        "reference_qa_results",
        "source_artifact",
        "task_configuration",
        "timeout",
        "update_qa_results",
        "vendor",
    ],
    "blhc": [
        "arch_all_build_architecture",
        "codename",
        "enable_regression_tracking",
        "extra_flags",
        "package_build_logs",
        "prefix",
        "qa_suite",
        "reference_prefix",
        "reference_qa_results",
        "source_artifact",
        "task_configuration",
        "update_qa_results",
        "vendor",
    ],
    "create_experiment_workspace": [
        "experiment_name",
        "expiration_delay",
        "owner_group",
        "public",
        "task_configuration",
        "workflow_template_names",
    ],
    "debdiff": [
        "arch_all_build_architecture",
        "binary_artifacts",
        "codename",
        "extra_flags",
        "original",
        "source_artifact",
        "task_configuration",
        "vendor",
    ],
    "debian_pipeline": [
        "arch_all_build_architecture",
        "architectures",
        "architectures_allowlist",
        "architectures_denylist",
        "autopkgtest_backend",
        "codename",
        "enable_autopkgtest",
        "enable_blhc",
        "enable_confirmation",
        "enable_debdiff",
        "enable_lintian",
        "enable_make_signed_source",
        "enable_piuparts",
        "enable_regression_tracking",
        "enable_reverse_dependencies_autopkgtest",
        "enable_upload",
        "extra_repositories",
        "lintian_backend",
        "lintian_fail_on_severity",
        "make_signed_source_key",
        "make_signed_source_purpose",
        "piuparts_backend",
        "piuparts_environment",
        "publish_replace",
        "qa_failure_policy",
        "qa_suite",
        "regression_tracking_qa_results",
        "sbuild_backend",
        "sbuild_environment_variant",
        "signing_template_names",
        "source_artifact",
        "suite",
        "task_configuration",
        "upload_binary_key",
        "upload_delayed_days",
        "upload_include_binaries",
        "upload_include_source",
        "upload_key",
        "upload_merge_uploads",
        "upload_require_signature",
        "upload_since_version",
        "upload_target",
        "upload_target_distribution",
        "vendor",
    ],
    "lintian": [
        "arch_all_build_architecture",
        "architectures",
        "backend",
        "binary_artifacts",
        "codename",
        "enable_regression_tracking",
        "exclude_tags",
        "fail_on_severity",
        "include_tags",
        "output",
        "prefix",
        "qa_suite",
        "reference_prefix",
        "reference_qa_results",
        "source_artifact",
        "task_configuration",
        "update_qa_results",
        "vendor",
    ],
    "make_signed_source": [
        "architectures",
        "binary_artifacts",
        "codename",
        "key",
        "prefix",
        "purpose",
        "sbuild_backend",
        "signing_template_artifacts",
        "task_configuration",
        "vendor",
    ],
    "noop": ["task_configuration"],
    "package_publish": [
        "binary_artifacts",
        "replace",
        "source_artifact",
        "suite_variables",
        "target_suite",
        "task_configuration",
        "unembargo",
        "update_indexes",
    ],
    "package_upload": [
        "arch_all_build_architecture",
        "binary_artifacts",
        "binary_key",
        "codename",
        "delayed_days",
        "key",
        "merge_uploads",
        "prefix",
        "require_signature",
        "since_version",
        "source_artifact",
        "target",
        "target_distribution",
        "task_configuration",
        "vendor",
    ],
    "piuparts": [
        "arch_all_build_architecture",
        "architectures",
        "backend",
        "binary_artifacts",
        "codename",
        "enable_regression_tracking",
        "environment",
        "extra_repositories",
        "prefix",
        "qa_suite",
        "reference_prefix",
        "reference_qa_results",
        "source_artifact",
        "task_configuration",
        "update_qa_results",
        "vendor",
    ],
    "qa": [
        "arch_all_build_architecture",
        "architectures",
        "architectures_allowlist",
        "architectures_denylist",
        "autopkgtest_backend",
        "binary_artifacts",
        "codename",
        "enable_autopkgtest",
        "enable_blhc",
        "enable_debdiff",
        "enable_lintian",
        "enable_piuparts",
        "enable_regression_tracking",
        "enable_reverse_dependencies_autopkgtest",
        "extra_repositories",
        "fail_on",
        "lintian_backend",
        "lintian_fail_on_severity",
        "package_build_logs",
        "piuparts_backend",
        "piuparts_environment",
        "prefix",
        "qa_suite",
        "reference_prefix",
        "reference_qa_results",
        "source_artifact",
        "task_configuration",
        "update_qa_results",
        "vendor",
    ],
    "reverse_dependencies_autopkgtest": [
        "arch_all_build_architecture",
        "architectures",
        "backend",
        "binary_artifacts",
        "codename",
        "context_artifacts",
        "debug_level",
        "enable_regression_tracking",
        "extra_repositories",
        "packages_allowlist",
        "packages_denylist",
        "prefix",
        "qa_suite",
        "reference_prefix",
        "reference_qa_results",
        "source_artifact",
        "task_configuration",
        "update_qa_results",
        "vendor",
    ],
    "sbuild": [
        "arch_all_build_architecture",
        "architectures",
        "backend",
        "binnmu",
        "build_profiles",
        "environment_variant",
        "extra_repositories",
        "input",
        "prefix",
        "retry_delays",
        "signing_template_names",
        "target_distribution",
        "task_configuration",
    ],
    "update_environments": ["targets", "task_configuration", "vendor"],
    "update_suite": ["suite_collection", "task_configuration"],
    "update_suites": [
        "force_basic_indexes",
        "only_suites",
        "task_configuration",
    ],
}


def set_workflowtemplate_runtime_parameters(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """Migrate existing Workflow Templates to use runtime_parameters."""
    WorkflowTemplate = apps.get_model("db", "WorkflowTemplate")

    for workflow_template in WorkflowTemplate.objects.all():
        for key in workflow_parameters.get(workflow_template.task_name, []):
            if key not in workflow_template.static_parameters:
                workflow_template.runtime_parameters[key] = RuntimeParameter.ANY
        workflow_template.save()


class Migration(migrations.Migration):
    dependencies = [
        ("db", "0033_workflowtemplate_add_runtime_parameters"),
    ]

    operations = [
        migrations.RunPython(
            set_workflowtemplate_runtime_parameters, migrations.RunPython.noop
        ),
    ]
