package jobs

import (
	"context"
	"os"
	"path/filepath"
	"time"

	"quyun/app/models"
	"quyun/database/fields"
	"quyun/database/schemas/public/model"
	"quyun/pkg/utils"
	"quyun/providers/ali"
	"quyun/providers/app"
	"quyun/providers/job"

	"github.com/pkg/errors"
	. "github.com/riverqueue/river"
	log "github.com/sirupsen/logrus"
	_ "go.ipao.vip/atom"
	"go.ipao.vip/atom/contracts"
)

var _ contracts.JobArgs = (*VideoExtractHeadImage)(nil)

type VideoExtractHeadImage struct {
	MediaHash string `json:"media_hash"`
}

func (s VideoExtractHeadImage) InsertOpts() InsertOpts {
	return InsertOpts{
		Queue:    QueueDefault,
		Priority: PriorityDefault,
	}
}

func (s VideoExtractHeadImage) Kind() string     { return "video_extract_head_image" }
func (a VideoExtractHeadImage) UniqueID() string { return a.Kind() }

var _ Worker[VideoExtractHeadImage] = (*VideoExtractHeadImageWorker)(nil)

// @provider(job)
type VideoExtractHeadImageWorker struct {
	WorkerDefaults[VideoExtractHeadImage]

	oss *ali.OSSClient
	job *job.Job
	app *app.Config
}

func (w *VideoExtractHeadImageWorker) NextRetry(job *Job[VideoExtractHeadImage]) time.Time {
	return time.Now().Add(30 * time.Second)
}

func (w *VideoExtractHeadImageWorker) Work(ctx context.Context, job *Job[VideoExtractHeadImage]) error {
	log := log.WithField("job", job.Args.Kind())

	log.Infof("[Start] Working on job with strings: %+v", job.Args)
	defer log.Infof("[End] Finished %s", job.Args.Kind())

	media, err := models.Medias.GetByHash(ctx, job.Args.MediaHash)
	if err != nil {
		log.Errorf("Error getting media by ID: %v", err)
		return JobCancel(err)
	}

	input := filepath.Join(w.app.StoragePath, media.Path)
	output := input[:len(input)-len(filepath.Ext(input))] + ".jpg"

	if err := utils.GetFrameImageFromVideo(input, output, 1); err != nil {
		log.Errorf("Error extracting image from video: %v", err)
		return errors.Wrap(err, "failed to extract image from video")
	}
	defer os.RemoveAll(output)

	fileSize, err := utils.GetFileSize(output)
	if err != nil {
		log.Errorf("Error getting file size: %v", err)
		return errors.Wrap(err, "failed to get file size")
	}

	fileMd5, err := utils.GetFileMd5(output)
	if err != nil {
		log.Errorf("Error getting file MD5: %v", err)
		return errors.Wrap(err, "failed to get file MD5")
	}
	filename := fileMd5 + filepath.Ext(output)

	name := "[展示图]" + media.Name + ".jpg"

	// create a new media record for the image
	imageMedia := &model.Medias{
		CreatedAt: time.Now(),
		Name:      name,
		MimeType:  "image/jpeg",
		Size:      fileSize,
		Path:      w.oss.GetSavePath(filename),
		Hash:      fileMd5,
		Metas: fields.ToJson(fields.MediaMetas{
			ParentHash: media.Hash,
		}),
	}

	// upload to oss
	if err := w.oss.Upload(ctx, output, imageMedia.Path, ali.WithInternal()); err != nil {
		log.Errorf("Error uploading image to OSS: %v", err)
		return errors.Wrap(err, "failed to upload image to OSS")
	}

	if w.job.Add(&RemoveFile{FilePath: output}); err != nil {
		log.Errorf("Error removing original file: %v", err)
	}

	if err := models.Medias.Create(ctx, imageMedia); err != nil {
		log.Errorf("Error creating media record: %v", err)
		return errors.Wrap(err, "failed to create media record")
	}

	dst := filepath.Join(w.app.StoragePath, media.Path)
	if w.job.Add(&RemoveFile{FilePath: dst}); err != nil {
		log.Errorf("Error removing original file: %v", err)
	}

	if w.job.Add(&PublishDraftPosts{MediaHash: media.Hash}); err != nil {
		log.Errorf("Error adding job: %v", err)
		return errors.Wrap(err, "failed to add job")
	}

	return nil
}
