package advice

import (
	"ai_scheduler/internal/biz"
	"ai_scheduler/internal/config"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg"
	"ai_scheduler/internal/pkg/file_download"
	"context"
	"errors"

	"net/url"

	"github.com/gofiber/fiber/v2"
)

// FileService 文件处理
type FileService struct {
	adviceBiz *biz.AdviceFileBiz
	cfg       *config.Config
}

// NewFileService
func NewFileService(
	adviceBiz *biz.AdviceFileBiz,
	cfg *config.Config,
) *FileService {
	return &FileService{
		adviceBiz: adviceBiz,
		cfg:       cfg,
	}
}

func (a *FileService) WordAna(c *fiber.Ctx) error {
	req := &entitys.WordAnaReq{}
	if err := c.BodyParser(req); err != nil {
		return err
	}
	// URL 解码
	fileURL, err := url.PathUnescape(req.WordFileUrl)
	if err != nil {
		return errors.New("URL 解码失败")
	}
	result, _, err := file_download.GetWordTextFromURL(fileURL, file_download.IsWordFile)
	if err != nil {
		return err
	}
	ana, err := a.adviceBiz.WordAna(context.Background(), result)
	if err != nil {
		return err
	}
	err = c.JSON(ana)
	return err
}

func (a *FileService) WordAnat(path string) ([]byte, error) {

	// URL 解码
	fileURL, err := url.PathUnescape(path)
	if err != nil {
		return nil, errors.New("URL 解码失败")
	}
	result, _, err := file_download.GetWordTextFromURL(fileURL, file_download.IsWordFile)
	if err != nil {
		return nil, err
	}
	ana, err := a.adviceBiz.WordAna(context.Background(), result)
	if err != nil {
		return nil, err
	}

	return pkg.JsonByteIgonErr(ana), err
}
