package ports

import (
	"time"
	"context"

	"github.com/dtoro/oikos/internal/core/domain"
	"github.com/dtoro/oikos/internal/ontology"
)

// TypeTree is the loaded ontology: entity types, relationship types,
// lifecycle definitions. It is ontology's pure tree behind an interface so
// ports does not alias a concrete struct into the contract.
type TypeTree = *ontology.TypeTree

// EntityFilters bounds entity list/search reads.
type EntityFilters struct {
	Type   string
	State  string
	Q      string
	Domain string
	Layer  string
	Cursor string
	Limit  int
}

// DerivedCheck is one concrete check derived from an entity's type
// monitoring spec, to be written in the same transaction as the entity
// mutation that produced it.
type DerivedCheck struct {
	Kind      string
	Config    map[string]any
	IntervalS int
}

// Idempotency replays-protects one command: the adapter stores the cached
// response inside the same transaction as the mutation, so a crash between
// the two cannot let a replay re-execute. RenderBody is a pure presenter
// closure that serializes the committed entity into the caller's wire
// shape; the repository never inspects it.
type Idempotency struct {
	Actor       string
	Key         string
	RequestHash string
	RenderBody  func(domain.Entity) []byte
}

// IdempotentResponse is a previously cached response for (actor, key).
type IdempotentResponse struct {
	RequestHash   string
	ResponseCode  int
	ResponseBody  []byte
}

// EntityCreateInput is one transaction: the entity, its derived check
// definitions, and the audit/event side-effects of the creation.
type EntityCreateInput struct {
	Entity        domain.Entity
	DerivedChecks []DerivedCheck
	Audit         []AuditEntry
	Event         *Event
	Idempotency   *Idempotency
	// EnrolledAt, when set, stamps the entities.enrolled_at column (the
	// client-enrollment / provisioning marker). Zero for ordinary creates.
	EnrolledAt *time.Time
}

// EntityUpdateInput mutates an entity atomically. ExpectedVersion is the
// optimistic-concurrency check (0 disables it). When RederiveChecks is set,
// the repository re-derives default checks inside the transaction — the
// graph host fallback (a service inherits its container's address) reads
// relationships through the open transaction, so derivation cannot happen
// in the service for updates.
type EntityUpdateInput struct {
	Entity          domain.Entity
	ExpectedVersion int
	RederiveChecks  bool
	Audit           []AuditEntry
	Event           *Event
	Idempotency     *Idempotency
}

// EntityTransitionInput is a lifecycle state change: the declared-transition
// check and preconditions are validated inside the transaction
// (check-then-act), not against the possibly-stale From.
type EntityTransitionInput struct {
	Slug  string
	From  string
	To    string
	Audit []AuditEntry
	Event *Event
}

// EntityRepository is the entity aggregate. Command methods are
// transaction-scoped: everything in the input commits or nothing does.
type EntityRepository interface {
	Get(ctx context.Context, id domain.UUID) (domain.Entity, error)
	BySlug(ctx context.Context, slug string) (domain.Entity, error)
	List(ctx context.Context, filters EntityFilters) ([]domain.Entity, string, error)
	Search(ctx context.Context, q string, limit int) ([]domain.Entity, error)

	Create(ctx context.Context, input EntityCreateInput) (domain.Entity, error)
	Update(ctx context.Context, input EntityUpdateInput) (domain.Entity, error)
	SetState(ctx context.Context, input EntityTransitionInput) (domain.Entity, error)

	// GetIdempotent returns the cached response for (actor, key), or
	// domain.ErrNotFound when none exists.
	GetIdempotent(ctx context.Context, actor, key string) (IdempotentResponse, error)
}

// RelationshipCreateInput validates endpoints against the ontology in core
// before this is called; the repository persists the edge (+audit/event).
type RelationshipCreateInput struct {
	Relationship domain.Relationship
	Audit        []AuditEntry
	Event        *Event
}

// RelationshipRepository is the relationship aggregate.
type RelationshipRepository interface {
	Create(ctx context.Context, input RelationshipCreateInput) (domain.Relationship, error)
	End(ctx context.Context, source, target domain.UUID, relType string) error
	ListFor(ctx context.Context, entityID domain.UUID, direction string) ([]domain.Relationship, error)
}

// EntityWithHealth pairs an entity with its probe health (from the
// entity_status join — the read shape graph/report endpoints need).
type EntityWithHealth struct {
	Entity      domain.Entity
	Health      string
	LastCheckAt *time.Time
}

// ReadModels surfaces query-shaped report reads consumed directly by the
// httpapi/mcpserver adapters (no service hop — invariant-free reads, plan
// §3.4). Methods accrete per phase as report handlers rewire.
type ReadModels interface {
	ListEntities(ctx context.Context, filters EntityFilters) ([]EntityWithHealth, string, error)
	GetEntity(ctx context.Context, id domain.UUID) (EntityWithHealth, error)
	GetEntityBySlug(ctx context.Context, slug string) (EntityWithHealth, error)
	GetEntityRelations(ctx context.Context, entityID domain.UUID, direction, relType string) ([]domain.Relationship, error)
	GetBlastRadius(ctx context.Context, entityID domain.UUID, depth int) ([]EntityWithHealth, error)
	GetGraph(ctx context.Context, depth int, root *domain.UUID, relTypes []string, cap int) (nodes []EntityWithHealth, edges []domain.Relationship, truncated bool, err error)
	ListEntityTypes(ctx context.Context) ([]domain.EntityType, error)
}

// OntologyStore loads the type tree; implementations cache. Consumers
// validate entity types, relationship endpoints, and lifecycle transitions
// against it before issuing repository writes.
type OntologyStore interface {
	LoadTypeTree(ctx context.Context) (TypeTree, error)
}
