// Package filters — discover.go
//
// v0.29.0 CS3: Discovers active Starlark packages with
// filters.pre_completion permission and registers them in the chain.
// Called at startup and after package install/permission changes.
package filters

import (
	"context"
	"log"

	"chat-switchboard/models"
	"chat-switchboard/sandbox"
	"chat-switchboard/store"
)

// DiscoverStarlarkFilters scans the package registry for active starlark
// extensions with granted filters.pre_completion permission and registers
// them in the filter chain. Extension filters start at order 100.
//
// Called once at startup. Future: also called on package install/activate
// to hot-register new filters without restart.
func DiscoverStarlarkFilters(ctx context.Context, chain *Chain, stores store.Stores, runner *sandbox.Runner) {
	if stores.ExtPermissions == nil || stores.Packages == nil {
		return
	}

	pkgs, err := stores.Packages.ListEnabledByType(ctx, "extension")
	if err != nil {
		log.Printf("⚠ filter discovery: failed to list extensions: %v", err)
		return
	}

	// Also check "full" packages (surface + extension)
	fullPkgs, err := stores.Packages.ListEnabledByType(ctx, "full")
	if err == nil {
		pkgs = append(pkgs, fullPkgs...)
	}

	registered := 0
	for i := range pkgs {
		pkg := &pkgs[i]

		// Must be starlark tier and active
		if pkg.Tier != models.ExtTierStarlark {
			continue
		}
		if pkg.Status != models.PackageStatusActive {
			continue
		}

		// Must have the pre_completion filter permission granted
		granted, err := stores.ExtPermissions.GrantedForPackage(ctx, pkg.ID)
		if err != nil {
			continue
		}

		hasFilterPerm := false
		for _, p := range granted {
			if p == models.ExtPermFiltersPreCompletion {
				hasFilterPerm = true
				break
			}
		}
		if !hasFilterPerm {
			continue
		}

		// Must have a starlark script
		if _, ok := pkg.Manifest["_starlark_script"].(string); !ok {
			continue
		}

		// Register with order 100+ (extension range, after built-ins)
		order := 100 + registered
		chain.Register(NewStarlarkFilter(runner, pkg, order))
		registered++
	}

	if registered > 0 {
		log.Printf("  🔗 Discovered %d Starlark pre-completion filter(s)", registered)
	}
}
