package commands

import (
	"fmt"

	"github.com/tanagram/cli/storage"
)

// List displays all cached policies
func List() error {
	// Find git root
	gitRoot, err := storage.FindGitRoot()
	if err != nil {
		return err
	}

	// Load cache
	cache, err := storage.LoadCache(gitRoot)
	if err != nil {
		return fmt.Errorf("failed to load cache: %w", err)
	}

	if len(cache.Policies) == 0 {
		fmt.Println("No cached policies found. Run 'tanagram sync' first.")
		return nil
	}

	totalPolicies := 0

	fmt.Println("Cached Policies (All enforced via LLM):")

	// Display policies grouped by file
	for filepath, serializablePolicies := range cache.Policies {
		if len(serializablePolicies) == 0 {
			continue
		}

		fmt.Printf("📄 %s (%d policies)\n", filepath, len(serializablePolicies))
		fmt.Println("─────────────────────────────────────────────────────────────")

		for _, sp := range serializablePolicies {
			totalPolicies++
			fmt.Printf("  • %s: %s\n", sp.Name, sp.Message)
		}
		fmt.Println()
	}

	// Summary
	fmt.Println("═════════════════════════════════════════════════════════════")
	fmt.Printf("Total: %d policies\n", totalPolicies)
	fmt.Printf("Files: %d\n", len(cache.Policies))
	fmt.Println("\nAll policies are enforced using LLM-based semantic analysis")

	return nil
}
