// Package scheduler provides automatic update scheduling.
package scheduler

import (
	"context"
	"fmt"
	"time"

	"github.com/robfig/cron/v3"
	"github.com/yourorg/devour/pkg/types"
)

// Config holds scheduler configuration.
type Config struct {
	Enabled     bool          `yaml:"enabled"`
	Interval    time.Duration `yaml:"interval"`
	CheckMethod string        `yaml:"check_method"`
	OnStartup   bool          `yaml:"on_startup"`
}

// Scheduler manages automatic source updates.
type Scheduler struct {
	config  *Config
	cron    *cron.Cron
	sources []*types.Source
}

// New creates a new scheduler.
func New(config *Config) *Scheduler {
	return &Scheduler{
		config: config,
		cron:   cron.New(cron.WithSeconds()),
	}
}

// AddSource adds a source to be monitored.
func (s *Scheduler) AddSource(source *types.Source) {
	s.sources = append(s.sources, source)
}

// Start begins the scheduling loop.
func (s *Scheduler) Start(ctx context.Context) error {
	if !s.config.Enabled {
		return nil
	}

	// Schedule sync job
	schedule := "@every 72h"
	if s.config.Interval > 0 {
		schedule = "@every " + s.config.Interval.String()
	}

	if _, err := s.cron.AddFunc(schedule, func() {
		s.syncAll(ctx)
	}); err != nil {
		return fmt.Errorf("failed to schedule sync job: %w", err)
	}

	s.cron.Start()
	return nil
}

// Stop halts the scheduler.
func (s *Scheduler) Stop() {
	s.cron.Stop()
}

func (s *Scheduler) syncAll(ctx context.Context) {
	// TODO: Implement sync logic
	// For each source:
	// 1. Check for changes
	// 2. If changed, re-scrape and re-index
}
