// Package doctor implements pre-flight checks, environment health reporting,
// and stub contract drift detection. Doctor is read-only — it never modifies
// state.
package doctor

import (
	"github.com/tidbcloud/controlplane9/internal/config"
	"github.com/tidbcloud/controlplane9/internal/host"
)

// Options configures a doctor run.
type Options struct {
	// AWSProfile is the AWS profile to check credentials for.
	AWSProfile string

	// Session is the active v1alpha2 session contract when the caller uses unified config.
	Session *config.SessionConfig

	// OwnerAllowlist carries the legacy CI-owner allowlist for owner resolution.
	OwnerAllowlist map[string][]string

	// Host is the selected host/session contract to validate and probe.
	Host *host.Session

	// StateDir is the cp9 session state directory (for example ".cp9/<name>").
	StateDir string

	// AllNamespaces checks every namespace instead of the host's primary namespace.
	AllNamespaces bool
}

// Run executes all doctor checks and returns the aggregated result.
func Run(opts *Options) *Result {
	r := &Result{}
	if opts == nil {
		opts = &Options{}
	}

	// Pre-flight checks.
	RunPreflightChecks(r, opts.AWSProfile, opts.Host, opts.Session, opts.OwnerAllowlist)

	// Stub contract drift.
	stateDir := opts.StateDir
	if stateDir == "" {
		stateDir = ".cp9"
	}
	if opts.Session != nil && opts.Session.APIVersion == config.APIVersionV1Alpha2 {
		CheckLocalPressure(r, opts.Session)
	}
	stubs := DiscoverStubs(stateDir)
	CheckStubDrift(r, stubs)
	CheckRecordingStubContracts(r, stubs)

	// Environment health (only if cluster name is provided).
	RunHealthChecks(r, opts.Host, opts.AllNamespaces)

	var personaName string
	if opts.Session != nil && opts.Session.APIVersion == config.APIVersionV1Alpha2 {
		personaName = config.SessionPersona(opts.Session)
	}
	var hostMode string
	if opts.Host != nil {
		hostMode = string(opts.Host.Mode)
	}
	r.AnnotateContext(personaName, hostMode)

	return r
}
