// Package gap implements the Regulatory Gap Analysis Engine.
//
// Given a product profile, the engine determines which regulations apply,
// identifies gaps against Master Controls, and produces a prioritized
// action list.
package gap

import (
	"time"

	"github.com/google/uuid"
)

// ── Product Profile ─────────────────────────────────────────────────

// ProductType classifies the product category.
type ProductType string

const (
	ProductTypeSoftware      ProductType = "software"
	ProductTypeHardware      ProductType = "hardware"
	ProductTypeIoT           ProductType = "iot"
	ProductTypeSaaS          ProductType = "saas"
	ProductTypeExchange      ProductType = "exchange"
	ProductTypeMedicalDevice ProductType = "medical_device"
	ProductTypeMachinery     ProductType = "machinery"
	ProductTypeOther         ProductType = "other"
)

// ProductProfile describes a customer's product for gap analysis.
type ProductProfile struct {
	ID          uuid.UUID   `json:"id" db:"id"`
	TenantID    uuid.UUID   `json:"tenant_id" db:"tenant_id"`
	Name        string      `json:"name" db:"name"`
	Description string      `json:"description" db:"description"`
	ProductType ProductType `json:"product_type" db:"product_type"`

	// Technology stack
	Technologies []string `json:"technologies" db:"-"` // encryption, api, blockchain, ai, ota_updates, cloud
	// Data processing categories
	DataProcessing []string `json:"data_processing" db:"-"` // personal_data, health_data, financial_data, telemetry
	// Target markets
	Markets []string `json:"markets" db:"-"` // EU, DE, AT, CH, US

	// Boolean flags (derived from technologies or set explicitly)
	ConnectedToInternet     bool `json:"connected_to_internet" db:"connected_to_internet"`
	HasSoftwareUpdates      bool `json:"has_software_updates" db:"has_software_updates"`
	UsesAI                  bool `json:"uses_ai" db:"uses_ai"`
	ProcessesPersonalData   bool `json:"processes_personal_data" db:"processes_personal_data"`
	IsCriticalInfraSupplier bool `json:"is_critical_infra_supplier" db:"is_critical_infra_supplier"`

	// Existing certifications (reduces gap count)
	ExistingCertifications []string `json:"existing_certifications" db:"-"` // ISO27001, CE, SOC2

	// ── IST-Zustand (was hat der Hersteller bereits?) ──────────────

	// Verbindung zu bestehendem IACE Projekt
	IACEProjectID *uuid.UUID `json:"iace_project_id" db:"iace_project_id"`

	// Angewandte Normen
	AppliedNorms []string `json:"applied_norms" db:"-"` // ISO12100, EN61326, EN62368

	// Bestehende Dokumentation
	HasRiskAssessment  bool `json:"has_risk_assessment" db:"has_risk_assessment"`
	HasTechnicalFile   bool `json:"has_technical_file" db:"has_technical_file"`
	HasOperatingManual bool `json:"has_operating_manual" db:"has_operating_manual"`
	HasSBOM            bool `json:"has_sbom" db:"has_sbom"`

	// Bestehende Prozesse
	HasVulnManagement   bool `json:"has_vuln_management" db:"has_vuln_management"`
	HasUpdateMechanism  bool `json:"has_update_mechanism" db:"has_update_mechanism"`
	HasIncidentResponse bool `json:"has_incident_response" db:"has_incident_response"`
	HasSupplyChainMgmt  bool `json:"has_supply_chain_mgmt" db:"has_supply_chain_mgmt"`

	// CE/Produktsicherheit
	CEMarkingSince *string `json:"ce_marking_since" db:"ce_marking_since"`
	ProductAge     string  `json:"product_age" db:"product_age"`

	// Metadata
	CreatedAt time.Time `json:"created_at" db:"created_at"`
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}

// ── Regulation Classification ───────────────────────────────────────

// RegulationID identifies a regulation.
type RegulationID string

const (
	RegCRA      RegulationID = "cra"
	RegAIAct    RegulationID = "ai_act"
	RegNIS2     RegulationID = "nis2"
	RegDSGVO    RegulationID = "dsgvo"
	RegDataAct  RegulationID = "data_act"
	RegMiCA     RegulationID = "mica"
	RegPSD2     RegulationID = "psd2"
	RegAML      RegulationID = "aml"
	RegMDR      RegulationID = "mdr"
	RegMachinery RegulationID = "machinery_regulation"
	RegEAA      RegulationID = "eaa"
	RegTDDDG    RegulationID = "tdddg"
	RegLkSG     RegulationID = "lksg"
)

// ApplicableRegulation describes a regulation that applies to a product.
type ApplicableRegulation struct {
	ID           RegulationID `json:"id"`
	Name         string       `json:"name"`
	Applicable   bool         `json:"applicable"`
	Confidence   float64      `json:"confidence"`
	Reasoning    string       `json:"reasoning"`
	Deadline     *time.Time   `json:"deadline,omitempty"`
	RiskLevel    string       `json:"risk_level"` // high, medium, low
	Requirements []string     `json:"requirements,omitempty"`
}

// ── Gap Analysis ────────────────────────────────────────────────────

// GapStatus indicates how well a control is fulfilled.
type GapStatus string

const (
	GapFulfilled GapStatus = "fulfilled"
	GapPartial   GapStatus = "partial"
	GapMissing   GapStatus = "missing"
	GapUnclear   GapStatus = "unclear"
)

// GapItem represents a single gap finding.
type GapItem struct {
	MCID          string       `json:"mc_id"`
	MCName        string       `json:"mc_name"`
	Regulation    RegulationID `json:"regulation"`
	Status        GapStatus    `json:"status"`
	Title         string       `json:"title"`
	Description   string       `json:"description"`
	Severity      string       `json:"severity"` // CRITICAL, HIGH, MEDIUM, LOW
	Priority      Priority     `json:"priority"`
	Recommendation string      `json:"recommendation"`
	ControlCount  int          `json:"control_count"`
}

// Priority determines the order of action.
type Priority struct {
	Score          float64 `json:"score"`
	SeverityFactor float64 `json:"severity_factor"`
	DeadlineFactor float64 `json:"deadline_factor"`
	DependencyFactor float64 `json:"dependency_factor"`
	Rank           int     `json:"rank"`
}

// ── Gap Report ──────────────────────────────────────────────────────

// GapReport is the full analysis result.
type GapReport struct {
	ProfileID   uuid.UUID              `json:"profile_id"`
	ProfileName string                 `json:"profile_name"`
	Regulations []ApplicableRegulation `json:"regulations"`
	Summary     GapSummary             `json:"summary"`
	Gaps        []GapItem              `json:"gaps"`
	CreatedAt   time.Time              `json:"created_at"`
}

// GapSummary provides aggregate statistics.
type GapSummary struct {
	TotalApplicableRegulations int            `json:"total_applicable_regulations"`
	TotalGaps                  int            `json:"total_gaps"`
	GapsByStatus               map[string]int `json:"gaps_by_status"`
	GapsBySeverity             map[string]int `json:"gaps_by_severity"`
	GapsByRegulation           map[string]int `json:"gaps_by_regulation"`
	OverallCompliancePercent   float64        `json:"overall_compliance_percent"`
	EstimatedEffortWeeks       float64        `json:"estimated_effort_weeks"`
}
