/*
Copyright 2025.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"context"
	"fmt"

	"github.com/go-logr/logr"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"

	gitopsv1alpha1 "freeleaps.com/gitops/initializer/api/v1alpha1"
	"freeleaps.com/gitops/initializer/internal/helm"
	"freeleaps.com/gitops/initializer/internal/metrics"
	"freeleaps.com/gitops/initializer/internal/repo"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
)

// ProjectInitializeReconciler reconciles a ProjectInitialize object
type ProjectInitializeReconciler struct {
	client.Client
	Scheme            *runtime.Scheme
	Log               logr.Logger
	GitOpsRepoManager repo.RepoManager
}

// +kubebuilder:rbac:groups=gitops.freeleaps.com,resources=projectinitializes,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=gitops.freeleaps.com,resources=projectinitializes/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=gitops.freeleaps.com,resources=projectinitializes/finalizers,verbs=update
// +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the ProjectInitialize object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.19.0/pkg/reconcile
func (r *ProjectInitializeReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	metrics.ReconcilesTotal.Inc()

	log := r.Log.WithValues("projectinitialize", req.NamespacedName)

	// fetch the ProjectInitialize instance
	cr := &gitopsv1alpha1.ProjectInitialize{}
	err := r.Get(ctx, req.NamespacedName, cr)
	if err != nil {
		if errors.IsNotFound(err) {
			log.Info("ProjectInitialize resource not found. Ignoring since object must be deleted")
			return ctrl.Result{}, nil
		} else {
			meta.SetStatusCondition(&cr.Status.Conditions, metav1.Condition{
				Type:               gitopsv1alpha1.ConditionOperatorDegraded,
				Status:             metav1.ConditionTrue,
				Reason:             gitopsv1alpha1.ReasonCustomResourceNotAvailable,
				LastTransitionTime: metav1.Now(),
				Message:            fmt.Sprintf("Unable to get ProjectInitialize instance: %s", err.Error()),
			})
			log.Error(err, "Failed to get ProjectInitialize")
			return ctrl.Result{}, utilerrors.NewAggregate([]error{err, r.Status().Update(ctx, cr)})
		}
	}

	// reconcile helm package for the ProjectInitialize instance
	if err := r.reconcileHelmPackage(logr.NewContext(ctx, log), cr); err != nil {
		meta.SetStatusCondition(&cr.Status.Conditions, metav1.Condition{
			Type:               gitopsv1alpha1.ConditionOperatorDegraded,
			Status:             metav1.ConditionTrue,
			Reason:             gitopsv1alpha1.ReasonHelmPackageGenerateFailed,
			LastTransitionTime: metav1.Now(),
			Message:            fmt.Sprintf("Failed to reconcile Helm package: %s", err.Error()),
		})
		log.Error(err, "Failed to reconcile Helm package")
		return ctrl.Result{}, utilerrors.NewAggregate([]error{err, r.Status().Update(ctx, cr)})
	} else {
		meta.SetStatusCondition(&cr.Status.Conditions, metav1.Condition{
			Type:               gitopsv1alpha1.ConditionHelmPackageGenerated,
			Status:             metav1.ConditionTrue,
			LastTransitionTime: metav1.Now(),
			Reason:             gitopsv1alpha1.ReasonHelmPackageGenerated,
			Message:            "The Helm package successful generated",
		})
		if err := r.Status().Update(ctx, cr); err != nil {
			log.Error(err, "Failed to update ProjectInitialize status")
			return ctrl.Result{}, err
		}
	}

	// reconcile Jenkinsfile for the ProjectInitialize instance

	return ctrl.Result{}, nil
}

func (r *ProjectInitializeReconciler) reconcileHelmPackage(ctx context.Context, cr *gitopsv1alpha1.ProjectInitialize) error {
	// retrieve logger
	log, err := logr.FromContext(ctx)
	if err != nil {
		return err
	}

	// check if already generated
	generated := meta.IsStatusConditionPresentAndEqual(cr.Status.Conditions, gitopsv1alpha1.ConditionHelmPackageGenerated, metav1.ConditionTrue)
	if generated {
		log.Info("Helm package already generated, skip reconcile for Helm package")
		return nil
	}

	if cr.Spec.Helm == nil {
		return fmt.Errorf("helm spec is missing")
	}

	// create helm package generator
	generator := helm.HelmGenerator{
		Instance: cr,
	}
	defer generator.Close()

	// generate helm package files into local tmp dir
	if err := generator.Generate(); err != nil {
		return err
	}

	requests := make([]repo.ChangeRequest, 0)

	// commit generated files to gitops repo
	err = generator.Walk(func(f *helm.HelmGeneratedFile) error {
		if blob, err := f.ReadAll(); err != nil {
			return err
		} else {
			req := repo.ChangeRequest{
				Path:      fmt.Sprintf("%s/helm-pkg/%s", cr.ObjectMeta.GetName(), f.QualifiedPath),
				Content:   blob,
				Operation: repo.OpCreate,
			}
			requests = append(requests, req)
		}
		return nil
	})
	if err != nil {
		return err
	}

	// apply changes to gitops repo
	if err := r.GitOpsRepoManager.ApplyChanges(ctx, requests, "chore(freeleaps-gitios-initializer): commit generated helm package"); err != nil {
		return err
	}

	return nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *ProjectInitializeReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&gitopsv1alpha1.ProjectInitialize{}).
		Complete(r)
}
