package audit

import (
	"encoding/json"
	"log"
	"os"
	"time"
)

// Logger writes structured audit events as single-line JSON to stdout (or a configured writer later).
type Logger struct {
	out   *log.Logger
	store EventStore
}

// NewLogger creates an audit logger.
func NewLogger(store EventStore) *Logger {
	return &Logger{out: log.New(os.Stdout, "", 0), store: store}
}

// Event is a governance audit record.
type Event struct {
	Type       string    `json:"type,omitempty"`
	Timestamp  time.Time `json:"timestamp"`
	TraceID    string    `json:"trace_id"`
	AgentID    string    `json:"agent_id"`
	Tool       string    `json:"tool"`
	Action     string    `json:"action"`
	Decision   string    `json:"decision"`
	Reason     string    `json:"reason,omitempty"`
	Policy     string    `json:"policy,omitempty"`
	Amount     *int64    `json:"amount,omitempty"`
	RiskScore  *float64  `json:"risk_score,omitempty"`
	HTTPPath        string   `json:"http_path,omitempty"`
	HTTPMethod      string   `json:"http_method,omitempty"`
	PrincipalSub    string   `json:"principal_sub,omitempty"`
	PrincipalRoles  []string `json:"principal_roles,omitempty"`
}

// Write serializes and writes one audit line.
func (l *Logger) Write(e Event) {
	e.Timestamp = time.Now().UTC()
	if l.store != nil {
		l.store.Add(e)
	}
	b, err := json.Marshal(e)
	if err != nil {
		l.out.Printf(`{"error":"audit_marshal_failed","message":%q}`, err.Error())
		return
	}
	l.out.Println(string(b))
}
