// @title Goyco API
// @version 0.1.1
// @description Goyco is a Y Combinator-style news aggregation platform API.
// @contact.name Goyco Team
// @contact.email sandro@cazzaniga.fr
// @license.name GPLv3
// @license.url https://www.gnu.org/licenses/gpl-3.0.html
// @host localhost:8080
// @schemes http
// @BasePath /api

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"goyco/cmd/goyco/commands"
	"goyco/docs"
	"goyco/internal/config"
	"goyco/internal/version"
)

func main() {
	loadDotEnv()

	commands.SetRunServer(runServerImpl)

	if len(os.Args) > 1 && os.Args[len(os.Args)-1] == "--daemon" {
		args := os.Args[1 : len(os.Args)-1]
		if err := commands.RunDaemonProcessDirect(args); err != nil {
			log.Fatalf("daemon error: %v", err)
		}
		return
	}

	if err := run(os.Args[1:]); err != nil {
		log.Fatalf("error: %v", err)
	}
}

func run(args []string) error {
	cfg, err := config.Load()
	if err != nil {
		return fmt.Errorf("load configuration: %w", err)
	}

	validator := commands.NewConfigValidator(nil)
	if err := validator.ValidateConfiguration(cfg); err != nil {
		return fmt.Errorf("configuration validation failed: %w", err)
	}

	docs.SwaggerInfo.Title = fmt.Sprintf("%s API", cfg.App.Title)
	docs.SwaggerInfo.Description = "Y Combinator-style news board API."
	docs.SwaggerInfo.Version = version.GetVersion()
	docs.SwaggerInfo.BasePath = "/api"
	docs.SwaggerInfo.Host = fmt.Sprintf("%s:%s", cfg.Server.Host, cfg.Server.Port)
	docs.SwaggerInfo.Schemes = []string{"http"}
	if cfg.Server.EnableTLS {
		docs.SwaggerInfo.Schemes = append(docs.SwaggerInfo.Schemes, "https")
	}

	root := buildRootCommand(cfg)
	runArgs := append([]string{os.Args[0]}, args...)
	return root.Run(context.Background(), runArgs)
}

func handleRunCommand(cfg *config.Config, args []string) error {
	fs := newFlagSet("run", printRunUsage)
	if err := parseCommand(fs, args, "run"); err != nil {
		if errors.Is(err, commands.ErrHelpRequested) {
			return nil
		}
		return err
	}

	if fs.NArg() > 0 {
		printRunUsage()
		return errors.New("unexpected arguments for run command")
	}

	return runServer(cfg, false)
}
