package main

import (
	"context"
	"encoding/json"
	"net/http"
	"time"
)

// ===== IoT Device Types =====

type IoTDevice struct {
	DeviceID         string    `json:"device_id"`
	DeviceName       string    `json:"device_name"`
	DeviceType       string    `json:"device_type"`
	LocationName     string    `json:"location_name"`
	Status           string    `json:"status"`
	LastReading      float64   `json:"last_reading"`
	LastReadingTime  string    `json:"last_reading_time"`
	Unit             string    `json:"unit"`
	BatteryLevel     *int      `json:"battery_level,omitempty"`
	SignalStrength   *int      `json:"signal_strength,omitempty"`
	DataPoints24h    []float64 `json:"data_points_24h,omitempty"`
}

type FlowMeter struct {
	IoTDevice
	FlowRateLps     float64 `json:"flow_rate_lps"`
	TotalVolume     float64 `json:"total_volume_m3"`
	AvgDailyFlow    float64 `json:"avg_daily_flow"`
	PeakFlow        float64 `json:"peak_flow"`
	PeakFlowTime    string  `json:"peak_flow_time"`
}

type FlowMeterSummary struct {
	TotalMeters      int     `json:"total_meters"`
	ActiveMeters     int     `json:"active_meters"`
	TotalFlowLps     float64 `json:"total_flow_lps"`
	AvgReliability   float64 `json:"avg_reliability"`
}

type FlowMeterData struct {
	Summary FlowMeterSummary `json:"summary"`
	Meters  []FlowMeter      `json:"meters"`
	Alerts  []interface{}    `json:"alerts"`
	Trends  []interface{}    `json:"trends"`
}

type PressureSensor struct {
	IoTDevice
	PressureBar      float64 `json:"pressure_bar"`
	MinPressureBar   float64 `json:"min_pressure_bar"`
	MaxPressureBar   float64 `json:"max_pressure_bar"`
	AvgPressureBar   float64 `json:"avg_pressure_bar"`
	PressureSpikeCount int    `json:"pressure_spike_count"`
}

type PressureSensorSummary struct {
	TotalSensors     int     `json:"total_sensors"`
	ActiveSensors    int     `json:"active_sensors"`
	AvgPressure      float64 `json:"avg_pressure"`
	SensorsInRange   int     `json:"sensors_in_range"`
	SensorsCritical  int     `json:"sensors_critical"`
}

type PressureSensorData struct {
	Summary PressureSensorSummary `json:"summary"`
	Sensors []PressureSensor      `json:"sensors"`
	Alerts  []interface{}         `json:"alerts"`
	Trends  []interface{}         `json:"trends"`
}

type ReservoirSensor struct {
	IoTDevice
	LevelMeters      float64 `json:"level_meters"`
	MaxLevelMeters   float64 `json:"max_level_meters"`
	MinLevelMeters   float64 `json:"min_level_meters"`
	VolumeMm3        float64 `json:"volume_m3"`
	CapacityM3       float64 `json:"capacity_m3"`
	CapacityPercent  float64 `json:"capacity_percent"`
	InflowLps        float64 `json:"inflow_lps"`
	OutflowLps       float64 `json:"outflow_lps"`
	NetFlowLps       float64 `json:"net_flow_lps"`
}

type ReservoirSensorSummary struct {
	TotalReservoirs    int     `json:"total_reservoirs"`
	ActiveSensors      int     `json:"active_sensors"`
	AvgCapacityPercent float64 `json:"avg_capacity_percent"`
	TotalVolumeMm3     float64 `json:"total_volume_m3"`
}

type ReservoirSensorData struct {
	Summary ReservoirSensorSummary `json:"summary"`
	Sensors []ReservoirSensor       `json:"sensors"`
	Alerts  []interface{}           `json:"alerts"`
	Trends  []interface{}           `json:"trends"`
}

type SmartMeter struct {
	IoTDevice
	MeterNumber       string  `json:"meter_number"`
	MeterType         string  `json:"meter_type"`
	CurrentReadingM3  float64 `json:"current_reading_m3"`
	ConsumptionLpd    float64 `json:"consumption_lpd"`
	TariffCategory    string  `json:"tariff_category"`
	ConnectionType    string  `json:"connection_type"`
	LastSyncTime      string  `json:"last_sync_time"`
	DataQualityPercent float64 `json:"data_quality_percent"`
}

type SmartMeterSummary struct {
	TotalMeters           int     `json:"total_meters"`
	ActiveMeters          int     `json:"active_meters"`
	TotalConsumptionLpd   float64 `json:"total_consumption_lpd"`
	AvgConsumptionPerMeter float64 `json:"avg_consumption_per_meter"`
	DataQualityAvg        float64 `json:"data_quality_avg"`
}

type SmartMeterData struct {
	Summary SmartMeterSummary `json:"summary"`
	Meters  []SmartMeter      `json:"meters"`
	Alerts  []interface{}     `json:"alerts"`
	Trends  []interface{}     `json:"trends"`
}

type WaterQualityProbe struct {
	IoTDevice
	PhValue            float64 `json:"ph_value"`
	TurbidityNtu       float64 `json:"turbidity_ntu"`
	TemperatureCelsius float64 `json:"temperature_celsius"`
	DissolvedOxygenMgl float64 `json:"dissolved_oxygen_mgl"`
	ConductivityMicros float64 `json:"conductivity_micros"`
	ChlorineResidual   float64 `json:"chlorine_residual"`
	CalibrationStatus  string  `json:"calibration_status"`
	LastCalibrationDate string `json:"last_calibration_date"`
}

type WaterQualitySummary struct {
	TotalProbes               int     `json:"total_probes"`
	ActiveProbes              int     `json:"active_probes"`
	AvgPh                     float64 `json:"avg_ph"`
	AvgTurbidity              float64 `json:"avg_turbidity"`
	AvgTemperature            float64 `json:"avg_temperature"`
	ProbesNeedingCalibration  int     `json:"probes_needing_calibration"`
}

type WaterQualityData struct {
	Summary WaterQualitySummary `json:"summary"`
	Probes  []WaterQualityProbe  `json:"probes"`
	Alerts  []interface{}        `json:"alerts"`
	Trends  []interface{}        `json:"trends"`
}

// ===== API Handlers =====

// GetIoTFlowMeters returns flow meter data for IoT dashboards
func GetIoTFlowMeters(db *DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
		defer cancel()

		// Query flow meter data from database
		// For now, return mock data structure - integrate with actual tables
		data := FlowMeterData{
			Summary: FlowMeterSummary{
				TotalMeters:    85,
				ActiveMeters:   82,
				TotalFlowLps:   1245,
				AvgReliability: 96.5,
			},
			Meters: []FlowMeter{},
			Alerts: []interface{}{},
			Trends: []interface{}{},
		}

		// Query from database (placeholder - add actual query)
		rows, err := db.pool.Query(ctx, `
			SELECT
				'FM' || LPAD(am.asset_id::text, 3, '0') as device_id,
				am.asset_name as device_name,
				'Flow Meter' as device_type,
				lm.location_name,
				'healthy' as status,
				RANDOM() * 1000 + 500 as last_reading,
				NOW()::text as last_reading_time,
				'LPS' as unit
			FROM ic3_asset_master am
			JOIN ic3_location_master lm ON am.location_id = lm.location_id
			WHERE am.asset_category ILIKE '%flow%'
			LIMIT 10
		`)

		if err == nil {
			defer rows.Close()
			for rows.Next() {
				var meter FlowMeter
				// Scan and populate meter data
				_ = meter
			}
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)
	}
}

// GetIoTPressureSensors returns pressure sensor data for IoT dashboards
func GetIoTPressureSensors(db *DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
		defer cancel()
		_ = ctx

		data := PressureSensorData{
			Summary: PressureSensorSummary{
				TotalSensors:    156,
				ActiveSensors:   152,
				AvgPressure:     3.2,
				SensorsInRange:  148,
				SensorsCritical: 2,
			},
			Sensors: []PressureSensor{},
			Alerts:  []interface{}{},
			Trends:  []interface{}{},
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)
	}
}

// GetIoTReservoirSensors returns reservoir level sensor data for IoT dashboards
func GetIoTReservoirSensors(db *DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
		defer cancel()
		_ = ctx

		data := ReservoirSensorData{
			Summary: ReservoirSensorSummary{
				TotalReservoirs:    8,
				ActiveSensors:      8,
				AvgCapacityPercent: 68.5,
				TotalVolumeMm3:     18750,
			},
			Sensors: []ReservoirSensor{},
			Alerts:  []interface{}{},
			Trends:  []interface{}{},
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)
	}
}

// GetIoTSmartMeters returns smart meter (AMR/AMI) data for IoT dashboards
func GetIoTSmartMeters(db *DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
		defer cancel()
		_ = ctx

		data := SmartMeterData{
			Summary: SmartMeterSummary{
				TotalMeters:           12450,
				ActiveMeters:          12380,
				TotalConsumptionLpd:   2850000,
				AvgConsumptionPerMeter: 230,
				DataQualityAvg:        94.2,
			},
			Meters: []SmartMeter{},
			Alerts: []interface{}{},
			Trends: []interface{}{},
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)
	}
}

// GetIoTWaterQualityProbes returns water quality probe data for IoT dashboards
func GetIoTWaterQualityProbes(db *DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
		defer cancel()
		_ = ctx

		data := WaterQualityData{
			Summary: WaterQualitySummary{
				TotalProbes:              24,
				ActiveProbes:             23,
				AvgPh:                    7.2,
				AvgTurbidity:             0.45,
				AvgTemperature:           24.5,
				ProbesNeedingCalibration: 2,
			},
			Probes: []WaterQualityProbe{},
			Alerts: []interface{}{},
			Trends: []interface{}{},
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)
	}
}
