package ucca

import (
	"time"

	"github.com/google/uuid"
)

// ============================================================================
// Output Structs
// ============================================================================

// AssessmentResult represents the complete evaluation result
type AssessmentResult struct {
	// Overall verdict
	Feasibility Feasibility `json:"feasibility"`
	RiskLevel   RiskLevel   `json:"risk_level"`
	Complexity  Complexity  `json:"complexity"`
	RiskScore   int         `json:"risk_score"` // 0-100

	// Triggered rules
	TriggeredRules []TriggeredRule `json:"triggered_rules"`

	// Required controls/mitigations
	RequiredControls []RequiredControl `json:"required_controls"`

	// Recommended architecture patterns
	RecommendedArchitecture []PatternRecommendation `json:"recommended_architecture"`

	// Patterns that must NOT be used
	ForbiddenPatterns []ForbiddenPattern `json:"forbidden_patterns"`

	// Matching didactic examples
	ExampleMatches []ExampleMatch `json:"example_matches"`

	// Special flags
	DSFARecommended bool            `json:"dsfa_recommended"`
	Art22Risk       bool            `json:"art22_risk"` // Art. 22 GDPR automated decision risk
	TrainingAllowed TrainingAllowed `json:"training_allowed"`

	// BetrVG (Works Council) assessment
	BetrvgConflictScore        int  `json:"betrvg_conflict_score,omitempty"`
	BetrvgConsultationRequired bool `json:"betrvg_consultation_required,omitempty"`

	// Intake reference for escalation logic
	Intake *UseCaseIntake `json:"intake,omitempty"`

	// Summary for humans
	Summary             string `json:"summary"`
	Recommendation      string `json:"recommendation"`
	AlternativeApproach string `json:"alternative_approach,omitempty"`
}

// TriggeredRule represents a rule that was triggered during evaluation
type TriggeredRule struct {
	Code        string   `json:"code"`        // e.g., "R-001"
	Category    string   `json:"category"`    // e.g., "A. Datenklassifikation"
	Title       string   `json:"title"`
	Description string   `json:"description"`
	Severity    Severity `json:"severity"`
	ScoreDelta  int      `json:"score_delta"`
	GDPRRef     string   `json:"gdpr_ref,omitempty"` // e.g., "Art. 9 DSGVO"
	Rationale   string   `json:"rationale"`          // Why this rule triggered
}

// RequiredControl represents a control that must be implemented
type RequiredControl struct {
	ID          string   `json:"id"`
	Title       string   `json:"title"`
	Description string   `json:"description"`
	Severity    Severity `json:"severity"`
	Category    string   `json:"category"` // "technical" or "organizational"
	GDPRRef     string   `json:"gdpr_ref,omitempty"`
}

// PatternRecommendation represents a recommended architecture pattern
type PatternRecommendation struct {
	PatternID   string `json:"pattern_id"` // e.g., "P-RAG-ONLY"
	Title       string `json:"title"`
	Description string `json:"description"`
	Rationale   string `json:"rationale"`
	Priority    int    `json:"priority"` // 1=highest
}

// ForbiddenPattern represents a pattern that must NOT be used
type ForbiddenPattern struct {
	PatternID   string `json:"pattern_id"`
	Title       string `json:"title"`
	Description string `json:"description"`
	Reason      string `json:"reason"`
	GDPRRef     string `json:"gdpr_ref,omitempty"`
}

// ExampleMatch represents a matching didactic example
type ExampleMatch struct {
	ExampleID   string  `json:"example_id"`
	Title       string  `json:"title"`
	Description string  `json:"description"`
	Similarity  float64 `json:"similarity"` // 0.0 - 1.0
	Outcome     string  `json:"outcome"`    // What happened / recommendation
	Lessons     string  `json:"lessons"`    // Key takeaways
}

// ============================================================================
// Database Entity
// ============================================================================

// Assessment represents a stored assessment in the database
type Assessment struct {
	ID            uuid.UUID  `json:"id"`
	TenantID      uuid.UUID  `json:"tenant_id"`
	NamespaceID   *uuid.UUID `json:"namespace_id,omitempty"`
	Title         string     `json:"title"`
	PolicyVersion string     `json:"policy_version"`
	Status        string     `json:"status"` // "completed", "draft"

	// Input
	Intake            UseCaseIntake `json:"intake"`
	UseCaseTextStored bool          `json:"use_case_text_stored"`
	UseCaseTextHash   string        `json:"use_case_text_hash"`

	// Results
	Feasibility             Feasibility             `json:"feasibility"`
	RiskLevel               RiskLevel               `json:"risk_level"`
	Complexity              Complexity              `json:"complexity"`
	RiskScore               int                     `json:"risk_score"`
	TriggeredRules          []TriggeredRule         `json:"triggered_rules"`
	RequiredControls        []RequiredControl       `json:"required_controls"`
	RecommendedArchitecture []PatternRecommendation `json:"recommended_architecture"`
	ForbiddenPatterns       []ForbiddenPattern      `json:"forbidden_patterns"`
	ExampleMatches          []ExampleMatch          `json:"example_matches"`
	DSFARecommended         bool                    `json:"dsfa_recommended"`
	Art22Risk               bool                    `json:"art22_risk"`
	TrainingAllowed         TrainingAllowed         `json:"training_allowed"`

	// Corpus Versioning (RAG)
	CorpusVersionID *uuid.UUID `json:"corpus_version_id,omitempty"`
	CorpusVersion   string     `json:"corpus_version,omitempty"`

	// LLM Explanation (optional)
	ExplanationText        *string    `json:"explanation_text,omitempty"`
	ExplanationGeneratedAt *time.Time `json:"explanation_generated_at,omitempty"`
	ExplanationModel       *string    `json:"explanation_model,omitempty"`

	// Domain
	Domain Domain `json:"domain"`

	// Audit
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedBy uuid.UUID `json:"created_by"`
}

// ============================================================================
// API Request/Response Types
// ============================================================================

// AssessRequest is the API request for creating an assessment
type AssessRequest struct {
	Intake UseCaseIntake `json:"intake"`
}

// AssessResponse is the API response for an assessment
type AssessResponse struct {
	Assessment Assessment       `json:"assessment"`
	Result     AssessmentResult `json:"result"`
	Escalation *Escalation      `json:"escalation,omitempty"`
}

// ExplainRequest is the API request for generating an explanation
type ExplainRequest struct {
	Language string `json:"language,omitempty"` // "de" or "en", default "de"
}

// ExplainResponse is the API response for an explanation
type ExplainResponse struct {
	ExplanationText string        `json:"explanation_text"`
	GeneratedAt     time.Time     `json:"generated_at"`
	Model           string        `json:"model"`
	LegalContext    *LegalContext `json:"legal_context,omitempty"`
}
