package scanner

import (
	"os"
	"path/filepath"
	"sort"
	"strings"
)

type ScanResult struct {
	Path        string `json:"path"`
	Size        int64  `json:"size"`
	IsDirectory bool   `json:"isDirectory"`
}

type DiskUsage struct {
	Name    string `json:"name"` // e.g. "Local Disk (C:)"
	TotalGB string `json:"totalGB"`
	UsedGB  string `json:"usedGB"`
	FreeGB  string `json:"freeGB"`
}

type CategorySizes struct {
	Documents       int64 `json:"documents"` // Personal Docs only
	Downloads       int64 `json:"downloads"`
	Desktop         int64 `json:"desktop"`
	Music           int64 `json:"music"`
	Movies          int64 `json:"movies"`
	System          int64 `json:"system"`
	Trash           int64 `json:"trash"`
	Apps            int64 `json:"apps"`
	Photos          int64 `json:"photos"`
	ICloud          int64 `json:"icloud"` // Or OneDrive on Windows?
	Archives        int64 `json:"archives"`
	VirtualMachines int64 `json:"virtual_machines"`
	Games           int64 `json:"games"`
	AI              int64 `json:"ai"`
	Docker          int64 `json:"docker"`
	Cache           int64 `json:"cache"`
}

type CleaningEstimates struct {
	FlashEst int64 `json:"flash_est"`
	DeepEst  int64 `json:"deep_est"`
}

// FindLargeFiles walks a directory and returns files > threshold
func FindLargeFiles(root string, threshold int64) ([]ScanResult, error) {
	var results []ScanResult

	err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
		if err != nil {
			return nil // Skip errors
		}

		// Skip hidden files/dirs (except .Trash maybe, but let's skip all . for now)
		if strings.HasPrefix(d.Name(), ".") {
			if d.IsDir() {
				return filepath.SkipDir
			}
			return nil
		}

		// Skip node_modules explicitly
		if d.IsDir() && d.Name() == "node_modules" {
			return filepath.SkipDir
		}

		if !d.IsDir() {
			info, err := d.Info()
			if err == nil && info.Size() > threshold {
				results = append(results, ScanResult{
					Path:        path,
					Size:        info.Size(),
					IsDirectory: false,
				})
			}
		}
		return nil
	})

	// Sort by size desc
	sort.Slice(results, func(i, j int) bool {
		return results[i].Size > results[j].Size
	})

	// Return top 50
	if len(results) > 50 {
		return results[:50], err
	}
	return results, err
}
