package controller

import (
	"fmt"
	"strings"

	"github.com/jfraeys/fetch_ml/cmd/tui/internal/model"
)

// Helper functions

func (c *Controller) getPathForStatus(status model.JobStatus) string {
	switch status {
	case model.StatusPending:
		return c.config.PendingPath()
	case model.StatusRunning:
		return c.config.RunningPath()
	case model.StatusFinished:
		return c.config.FinishedPath()
	case model.StatusFailed:
		return c.config.FailedPath()
	case model.StatusQueued:
		return c.config.PendingPath() // Queued jobs are in pending directory
	}
	return ""
}

func getSelectedJob(m model.State) *model.Job {
	if item := m.JobList.SelectedItem(); item != nil {
		if job, ok := item.(model.Job); ok {
			return &job
		}
	}
	return nil
}

func calculateJobStats(m *model.State) {
	m.JobStats = make(map[model.JobStatus]int)
	for _, job := range m.Jobs {
		m.JobStats[job.Status]++
	}
}

func formatStatus(m model.State) string {
	var parts []string

	if len(m.Jobs) > 0 {
		stats := []string{}
		if count := m.JobStats[model.StatusPending]; count > 0 {
			stats = append(stats, fmt.Sprintf("⏸ %d", count))
		}
		if count := m.JobStats[model.StatusRunning]; count > 0 {
			stats = append(stats, fmt.Sprintf("▶ %d", count))
		}
		if count := m.JobStats[model.StatusFinished]; count > 0 {
			stats = append(stats, fmt.Sprintf("%d", count))
		}
		if count := m.JobStats[model.StatusFailed]; count > 0 {
			stats = append(stats, fmt.Sprintf("✗ %d", count))
		}
		parts = append(parts, strings.Join(stats, " | "))
	}

	if len(m.QueuedTasks) > 0 {
		parts = append(parts, fmt.Sprintf("Queue: %d", len(m.QueuedTasks)))
	}

	parts = append(parts, fmt.Sprintf("Updated: %s", m.LastRefresh.Format("15:04:05")))

	return strings.Join(parts, " • ")
}
