package iace

// ============================================================================
// Constants / Enums
// ============================================================================

// ProjectStatus represents the lifecycle status of an IACE project
type ProjectStatus string

const (
	ProjectStatusDraft          ProjectStatus = "draft"
	ProjectStatusOnboarding     ProjectStatus = "onboarding"
	ProjectStatusClassification ProjectStatus = "classification"
	ProjectStatusHazardAnalysis ProjectStatus = "hazard_analysis"
	ProjectStatusMitigation     ProjectStatus = "mitigation"
	ProjectStatusVerification   ProjectStatus = "verification"
	ProjectStatusTechFile       ProjectStatus = "tech_file"
	ProjectStatusCompleted      ProjectStatus = "completed"
	ProjectStatusArchived       ProjectStatus = "archived"
)

// ComponentType represents the type of a system component
type ComponentType string

const (
	ComponentTypeSoftware   ComponentType = "software"
	ComponentTypeFirmware   ComponentType = "firmware"
	ComponentTypeAIModel    ComponentType = "ai_model"
	ComponentTypeHMI        ComponentType = "hmi"
	ComponentTypeSensor     ComponentType = "sensor"
	ComponentTypeActuator   ComponentType = "actuator"
	ComponentTypeController ComponentType = "controller"
	ComponentTypeNetwork    ComponentType = "network"
	ComponentTypeMechanical ComponentType = "mechanical"
	ComponentTypeElectrical ComponentType = "electrical"
	ComponentTypeOther      ComponentType = "other"
)

// RegulationType represents the applicable EU regulation
type RegulationType string

const (
	RegulationNIS2                RegulationType = "nis2"
	RegulationAIAct               RegulationType = "ai_act"
	RegulationCRA                 RegulationType = "cra"
	RegulationMachineryRegulation RegulationType = "machinery_regulation"
)

// HazardStatus represents the lifecycle status of a hazard
type HazardStatus string

const (
	HazardStatusIdentified HazardStatus = "identified"
	HazardStatusAssessed   HazardStatus = "assessed"
	HazardStatusMitigated  HazardStatus = "mitigated"
	HazardStatusAccepted   HazardStatus = "accepted"
	HazardStatusClosed     HazardStatus = "closed"
)

// HazardType distinguishes ISO 12100 concepts in the hazard chain:
// Hazard → Hazardous Situation → Harm
const (
	HazardTypeHazard             = "hazard"             // Source of potential harm (e.g. rotating shaft)
	HazardTypeHazardousSituation = "hazardous_situation" // Person exposed to hazard (e.g. operator near shaft)
	HazardTypeHarm               = "harm"               // Injury outcome (e.g. entanglement)
	DefaultHazardType            = HazardTypeHazardousSituation
)

// DeriveHazardType determines the ISO 12100 hazard type from the hazard's fields.
// If an explicit type is set, it is returned as-is. Otherwise:
//   - PossibleHarm filled + Scenario filled → "hazardous_situation" (most specific)
//   - Only PossibleHarm filled → "harm"
//   - Only TriggerEvent/Category → "hazard" (source only)
//   - Default fallback → "hazardous_situation"
func DeriveHazardType(h *Hazard) string {
	if h.HazardType != "" {
		return h.HazardType
	}
	if h.Scenario != "" && h.PossibleHarm != "" {
		return HazardTypeHazardousSituation
	}
	if h.PossibleHarm != "" && h.Scenario == "" {
		return HazardTypeHarm
	}
	if h.Scenario == "" && h.PossibleHarm == "" && h.Category != "" {
		return HazardTypeHazard
	}
	return DefaultHazardType
}

// FailureModeEntry represents a potential failure mode for a component type.
// Used for FMEA (Failure Mode and Effects Analysis) — the chain is:
// Component → FailureMode → HazardousSituation → Harm.
type FailureModeEntry struct {
	ID            string `json:"id"`             // e.g. "FM-SEN-01"
	ComponentType string `json:"component_type"` // e.g. "sensor", "controller"
	Mode          string `json:"mode"`           // e.g. "loss_of_signal", "drift"
	NameDE        string `json:"name_de"`
	NameEN        string `json:"name_en"`
	Effect        string `json:"effect"`          // System-level effect
	DetectionHint string `json:"detection_hint"`  // How to detect this failure
	// FMEA scores (each 1-10)
	DefaultSeverity   int `json:"default_severity"`   // Impact severity
	DefaultOccurrence int `json:"default_occurrence"`  // How often it occurs
	DefaultDetection  int `json:"default_detection"`   // Detectability (10=undetectable, 1=immediately detectable)
}

// CalculateRPZ computes the Risk Priority Number for a failure mode.
// RPZ = Severity × Occurrence × Detection. Range: 1-1000.
// RPZ > 100: action required. RPZ > 200: critical.
func (fm *FailureModeEntry) CalculateRPZ() int {
	return fm.DefaultSeverity * fm.DefaultOccurrence * fm.DefaultDetection
}

// RPZThresholdAction is the RPZ value above which corrective action is required.
const RPZThresholdAction = 100

// CalculateAP computes the AIAG-VDA Action Priority (H/M/L).
// Replaces pure RPN/RPZ with a 3D severity-occurrence-detection priority matrix
// per the AIAG-VDA FMEA Handbook (2019). Returns "H", "M", or "L".
func CalculateAP(s, o, d int) string {
	if s >= 9 {
		if o >= 4 || d >= 7 {
			return "H"
		}
		if o >= 2 || d >= 5 {
			return "M"
		}
		return "L"
	}
	if s >= 7 {
		if o >= 5 || d >= 8 {
			return "H"
		}
		if o >= 3 || d >= 5 {
			return "M"
		}
		return "L"
	}
	if s >= 5 {
		if o >= 7 || d >= 9 {
			return "H"
		}
		if o >= 4 || d >= 7 {
			return "M"
		}
		return "L"
	}
	// S < 5
	if o >= 8 && d >= 9 {
		return "H"
	}
	if o >= 6 || d >= 8 {
		return "M"
	}
	return "L"
}

// CalculateAPForFM computes AP for a FailureModeEntry.
func (fm *FailureModeEntry) CalculateAPForFM() string {
	return CalculateAP(fm.DefaultSeverity, fm.DefaultOccurrence, fm.DefaultDetection)
}

// AssessmentType represents the type of risk assessment
type AssessmentType string

const (
	AssessmentTypeInitial        AssessmentType = "initial"
	AssessmentTypePostMitigation AssessmentType = "post_mitigation"
	AssessmentTypeReassessment   AssessmentType = "reassessment"
)

// RiskLevel represents the severity level of a risk
type RiskLevel string

const (
	RiskLevelNotAcceptable RiskLevel = "not_acceptable" // ISO 12100 mode: > 300
	RiskLevelVeryHigh      RiskLevel = "very_high"      // ISO 12100 mode: 151-300
	RiskLevelCritical      RiskLevel = "critical"
	RiskLevelHigh          RiskLevel = "high"
	RiskLevelMedium        RiskLevel = "medium"
	RiskLevelLow           RiskLevel = "low"
	RiskLevelNegligible    RiskLevel = "negligible"
)

// ReductionType represents the type of risk reduction measure
type ReductionType string

const (
	ReductionTypeDesign      ReductionType = "design"
	ReductionTypeProtective  ReductionType = "protective"
	ReductionTypeInformation ReductionType = "information"
)

// MitigationStatus represents the lifecycle status of a mitigation measure
type MitigationStatus string

const (
	MitigationStatusPlanned     MitigationStatus = "planned"
	MitigationStatusImplemented MitigationStatus = "implemented"
	MitigationStatusVerified    MitigationStatus = "verified"
	MitigationStatusRejected    MitigationStatus = "rejected"
)

// VerificationMethod represents the method used for verification
type VerificationMethod string

const (
	VerificationMethodTest               VerificationMethod = "test"
	VerificationMethodAnalysis           VerificationMethod = "analysis"
	VerificationMethodInspection         VerificationMethod = "inspection"
	VerificationMethodReview             VerificationMethod = "review"
	VerificationMethodDesignReview       VerificationMethod = "design_review"
	VerificationMethodCalculation        VerificationMethod = "calculation"
	VerificationMethodTestReport         VerificationMethod = "test_report"
	VerificationMethodValidation         VerificationMethod = "validation"
	VerificationMethodElectricalTest     VerificationMethod = "electrical_test"
	VerificationMethodSoftwareTest       VerificationMethod = "software_test"
	VerificationMethodPenetrationTest    VerificationMethod = "penetration_test"
	VerificationMethodAcceptanceProtocol VerificationMethod = "acceptance_protocol"
	VerificationMethodUserTest           VerificationMethod = "user_test"
	VerificationMethodDocRelease         VerificationMethod = "documentation_release"
)

// TechFileSectionStatus represents the status of a technical file section
type TechFileSectionStatus string

const (
	TechFileSectionStatusDraft     TechFileSectionStatus = "draft"
	TechFileSectionStatusGenerated TechFileSectionStatus = "generated"
	TechFileSectionStatusReviewed  TechFileSectionStatus = "reviewed"
	TechFileSectionStatusApproved  TechFileSectionStatus = "approved"
)

// MonitoringEventType represents the type of monitoring event
type MonitoringEventType string

const (
	MonitoringEventTypeIncident         MonitoringEventType = "incident"
	MonitoringEventTypeUpdate           MonitoringEventType = "update"
	MonitoringEventTypeDriftAlert       MonitoringEventType = "drift_alert"
	MonitoringEventTypeRegulationChange MonitoringEventType = "regulation_change"
	MonitoringEventTypeAudit            MonitoringEventType = "audit"
)

// AuditAction represents the type of action recorded in the audit trail
type AuditAction string

const (
	AuditActionCreate  AuditAction = "create"
	AuditActionUpdate  AuditAction = "update"
	AuditActionDelete  AuditAction = "delete"
	AuditActionApprove AuditAction = "approve"
	AuditActionVerify  AuditAction = "verify"
)

// LifecyclePhase represents a machine lifecycle phase per ISO 12100 methodology
type LifecyclePhase string

const (
	LPTransport         LifecyclePhase = "transport"
	LPStorage           LifecyclePhase = "storage"
	LPAssembly          LifecyclePhase = "assembly"
	LPInstallation      LifecyclePhase = "installation"
	LPCommissioning     LifecyclePhase = "commissioning"
	LPParameterization  LifecyclePhase = "parameterization"
	LPSetup             LifecyclePhase = "setup"
	LPNormalOperation   LifecyclePhase = "normal_operation"
	LPAutoOperation     LifecyclePhase = "automatic_operation"
	LPManualOperation   LifecyclePhase = "manual_operation"
	LPTeachMode         LifecyclePhase = "teach_mode"
	LPProductionStart   LifecyclePhase = "production_start"
	LPProductionStop    LifecyclePhase = "production_stop"
	LPProcessMonitoring LifecyclePhase = "process_monitoring"
	LPCleaning          LifecyclePhase = "cleaning"
	LPMaintenance       LifecyclePhase = "maintenance"
	LPInspection        LifecyclePhase = "inspection"
	LPCalibration       LifecyclePhase = "calibration"
	LPFaultClearing     LifecyclePhase = "fault_clearing"
	LPRepair            LifecyclePhase = "repair"
	LPChangeover        LifecyclePhase = "changeover"
	LPSoftwareUpdate    LifecyclePhase = "software_update"
	LPRemoteMaintenance LifecyclePhase = "remote_maintenance"
	LPDecommissioning   LifecyclePhase = "decommissioning"
	LPDisposal          LifecyclePhase = "disposal"
)

// ReviewStatus represents the review state of a hazard assessment
type ReviewStatus string

const (
	ReviewStatusDraft    ReviewStatus = "draft"
	ReviewStatusInReview ReviewStatus = "in_review"
	ReviewStatusReviewed ReviewStatus = "reviewed"
	ReviewStatusApproved ReviewStatus = "approved"
	ReviewStatusRejected ReviewStatus = "rejected"
)
