/*
 * Copyright (c) 2025-2026, Антон Аксенов
 * This file is part of iptvc project
 * MIT License: https://git.axenov.dev/IPTV/iptvc/src/branch/master/LICENSE
 */

package cmd

import (
	"axenov/iptv-checker/app"
	"axenov/iptv-checker/app/checker"
	"axenov/iptv-checker/app/playlist"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/spf13/cobra"
)

// checkCmd represents the file command
var checkCmd = &cobra.Command{
	Use:   "check",
	Short: "Check playlists",
	Run: func(cmd *cobra.Command, args []string) {
		app.Init()
		applyAppOverrides(cmd)
		applyCacheOverrides(cmd)
		applyCheckOverrides(cmd)
		app.InitCache()

		currentIteration := 1
		for {
			if app.Args.RepeatCount != 1 {
				log.Printf(
					"@ New iteration current=%d count=%d\n",
					currentIteration,
					app.Args.RepeatCount,
				)
			}

			var lists []playlist.Playlist
			if len(app.Args.Files) == 0 && len(app.Args.Urls) == 0 && len(app.Args.Codes) == 0 {
				lists = checker.PrepareListsToCheck(app.Args.Files, app.Args.Urls, app.Args.Codes)
			} else {
				if currentIteration == 1 {
					lists = checker.PrepareListsToCheck(app.Args.Files, app.Args.Urls, app.Args.Codes)
				}
			}

			if len(lists) > 0 {
				startTime := time.Now()
				onlineCount, offlineCount := checker.CheckPlaylists(lists)

				log.Printf(
					"Done! count=%d online=%d offline=%d elapsedTime=%.2fs\n",
					len(lists),
					onlineCount,
					offlineCount,
					time.Since(startTime).Seconds(),
				)

				if app.Args.NeedJson {
					marshal, _ := json.Marshal(lists)
					fmt.Println(string(marshal))
				}
			} else {
				log.Println("There are no playlists to check")
			}

			if app.Args.RepeatCount != 0 {
				if uint(currentIteration) == app.Args.RepeatCount {
					break
				}
				currentIteration++
			}
			// AllCooldown хранится в миллисекундах, поэтому переводим в time.Millisecond
			cooldown := time.Duration(app.Config.Check.Playlists.AllCooldown.Value()) * time.Millisecond
			log.Printf("Waiting for new iteration... cooldown=%s\n", cooldown)
			time.Sleep(cooldown)
		}
	},
}

func init() {
	addCommonCheckFlags(checkCmd, 1)
	addCheckOnlyFlags(checkCmd)
	rootCmd.AddCommand(checkCmd)
}
