{
  "openapi": "3.1.0",
  "info": {
    "title": "Aerion Renewable Intelligence — Demonstration API",
    "version": "1.0.0",
    "description": "Public synthetic wind/solar telemetry. A browser-session cookie isolates simulated controls, archives, and reports. Initial reads replay five minutes of deterministic samples; live ingestion generates exactly fifty channels per second for the selected asset while viewed. Every generated channel is durably archived when storage=neon. demo-memory is an explicitly ephemeral local fallback. A two-hour batch cap applies per browser/farm/asset. No physical equipment is connected and no email is sent."
  },
  "servers": [
    {
      "url": "/"
    }
  ],
  "paths": {
    "/api/telemetry": {
      "get": {
        "summary": "Ingest a synthetic event-time batch and return the selected asset snapshot",
        "parameters": [
          {
            "$ref": "#/components/parameters/Farm"
          },
          {
            "$ref": "#/components/parameters/Asset"
          }
        ],
        "responses": {
          "200": {
            "description": "Archive commit succeeded; snapshot includes raw history and dedicated derived windows",
            "headers": {
              "Set-Cookie": {
                "description": "Opaque HttpOnly SameSite browser demo session",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TelemetrySnapshot"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "429": {
            "$ref": "#/components/responses/DemoLimit"
          },
          "503": {
            "$ref": "#/components/responses/Unavailable"
          }
        }
      }
    },
    "/api/stream": {
      "get": {
        "summary": "Stream selected-asset snapshots through server-sent events",
        "description": "Use EventSource. Named telemetry events carry TelemetrySnapshot JSON at approximately one-second intervals. Event id is event-time ISO timestamp. Connections last about24seconds and advertise retry:1000. Reconnects are safe: the raw batch key deduplicates repeated event seconds. Only committed data is emitted. A stream-error event reports an interruption or demo archive cap.",
        "parameters": [
          {
            "$ref": "#/components/parameters/Farm"
          },
          {
            "$ref": "#/components/parameters/Asset"
          }
        ],
        "responses": {
          "200": {
            "description": "Finite SSE stream with automatic EventSource reconnection",
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          }
        }
      }
    },
    "/api/history": {
      "get": {
        "summary": "Query archived raw measurements or dedicated derived windows",
        "parameters": [
          {
            "$ref": "#/components/parameters/Farm"
          },
          {
            "$ref": "#/components/parameters/Asset"
          },
          {
            "name": "kind",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "raw",
                "derived"
              ],
              "default": "raw"
            }
          },
          {
            "name": "metric",
            "in": "query",
            "description": "For kind=raw, use one of the fifty raw channel ids returned by telemetry. For kind=derived, use voltage_range_60s; voltage and the omitted/default metric are accepted aliases. Other raw metrics are rejected for derived history.",
            "schema": {
              "type": "string",
              "default": "voltage"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 1000,
              "default": 300
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Bounded chronological history with storage provenance",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "farmId": {
                      "$ref": "#/components/schemas/FarmId"
                    },
                    "assetId": {
                      "type": "string"
                    },
                    "metric": {
                      "type": "string"
                    },
                    "kind": {
                      "enum": [
                        "raw",
                        "derived"
                      ]
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "oneOf": [
                          {
                            "$ref": "#/components/schemas/HistoryPoint"
                          },
                          {
                            "$ref": "#/components/schemas/DerivedWindow"
                          }
                        ]
                      }
                    },
                    "storage": {
                      "$ref": "#/components/schemas/Storage"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "503": {
            "$ref": "#/components/responses/Unavailable"
          }
        }
      }
    },
    "/api/controls": {
      "get": {
        "summary": "Read simulated state and the last thirty acknowledged commands",
        "parameters": [
          {
            "$ref": "#/components/parameters/Farm"
          },
          {
            "$ref": "#/components/parameters/Asset"
          }
        ],
        "responses": {
          "200": {
            "description": "State and audit history for this browser session",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "state": {
                      "enum": [
                        "running",
                        "curtailed",
                        "maintenance"
                      ]
                    },
                    "commands": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/ControlCommand"
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          }
        }
      },
      "post": {
        "summary": "Acknowledge a simulated control command with an idempotent audit record",
        "description": "Same-origin JSON writes only. Curtail applies45% power, maintenance applies0% power/rotor speed, and resume restores nominal behavior to the next event second. No real equipment is controlled. Reusing a key with different content returns409. At most20commands per minute per browser session.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "farmId",
                  "assetId",
                  "action",
                  "idempotencyKey"
                ],
                "properties": {
                  "farmId": {
                    "$ref": "#/components/schemas/FarmId"
                  },
                  "assetId": {
                    "type": "string",
                    "example": "WTG-01"
                  },
                  "action": {
                    "enum": [
                      "curtail",
                      "resume",
                      "maintenance"
                    ]
                  },
                  "idempotencyKey": {
                    "type": "string",
                    "pattern": "^[a-zA-Z0-9_-]{8,80}$"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Acknowledged simulated command",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlCommand"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "403": {
            "description": "Cross-origin writes rejected"
          },
          "409": {
            "description": "Idempotency key content conflict"
          },
          "429": {
            "$ref": "#/components/responses/DemoLimit"
          },
          "503": {
            "$ref": "#/components/responses/Unavailable"
          }
        }
      }
    },
    "/api/reports": {
      "post": {
        "summary": "Analyze persisted finalized voltage windows and generate a report/email preview",
        "description": "Runs a short statistical analysis and an explicitly labeled exponential-smoothing baseline. It is not a trained ML model. The production architecture routes long-running analytics to durable batch workers. No email delivery occurs.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "farmId"
                ],
                "properties": {
                  "farmId": {
                    "$ref": "#/components/schemas/FarmId"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Completed persisted report with findings, statistics, and email.to/from/subject/html/text",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Report"
                }
              }
            }
          },
          "409": {
            "description": "No finalized windows; open a farm stream first"
          },
          "503": {
            "$ref": "#/components/responses/Unavailable"
          }
        }
      },
      "get": {
        "summary": "Read a persisted report in the current browser session",
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Persisted report",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Report"
                }
              }
            }
          },
          "404": {
            "description": "Report not found in this browser session"
          }
        }
      }
    },
    "/api/cron/reports": {
      "get": {
        "summary": "Run the scheduled demo report pipeline for up to twenty recently active session/farm pairs",
        "description": "Invoked daily by Vercel Cron. Requires the configured CRON_SECRET bearer token. Generates persisted report previews without sending email.",
        "security": [
          {
            "cronBearer": []
          }
        ],
        "responses": {
          "200": {
            "description": "Counts, generated report ids, and per-target failures"
          },
          "401": {
            "description": "Unauthorized"
          },
          "503": {
            "description": "Cron secret or storage unavailable"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "cronBearer": {
        "type": "http",
        "scheme": "bearer"
      }
    },
    "parameters": {
      "Farm": {
        "name": "farm",
        "in": "query",
        "schema": {
          "$ref": "#/components/schemas/FarmId"
        }
      },
      "Asset": {
        "name": "asset",
        "in": "query",
        "description": "WTG-01..WTG-12 for wind farms; INV-01..INV-12 for solar farms. Defaults to first asset.",
        "schema": {
          "type": "string",
          "example": "WTG-01"
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Invalid input",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "DemoLimit": {
        "description": "Bounded demo workload limit reached",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Unavailable": {
        "description": "Storage unavailable; no silent durable-storage fallback",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": [
          "error"
        ],
        "properties": {
          "error": {
            "type": "string"
          }
        }
      },
      "FarmId": {
        "type": "string",
        "enum": [
          "north-sea",
          "mojave",
          "jaisalmer",
          "patagonia"
        ],
        "default": "north-sea"
      },
      "Storage": {
        "type": "string",
        "enum": [
          "neon",
          "demo-memory"
        ]
      },
      "Signal": {
        "type": "object",
        "required": [
          "id",
          "label",
          "unit",
          "value"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "label": {
            "type": "string"
          },
          "unit": {
            "type": "string"
          },
          "value": {
            "type": "number"
          }
        }
      },
      "HistoryPoint": {
        "type": "object",
        "properties": {
          "timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "value": {
            "type": "number"
          }
        }
      },
      "DerivedWindow": {
        "type": "object",
        "required": [
          "windowStart",
          "windowEnd",
          "min",
          "max",
          "delta",
          "count",
          "status",
          "version",
          "quality"
        ],
        "properties": {
          "windowStart": {
            "type": "string",
            "format": "date-time"
          },
          "windowEnd": {
            "type": "string",
            "format": "date-time"
          },
          "min": {
            "type": "number"
          },
          "max": {
            "type": "number"
          },
          "delta": {
            "type": "number",
            "description": "max-min voltage in this60second event-time window"
          },
          "count": {
            "type": "integer",
            "minimum": 1,
            "maximum": 60
          },
          "status": {
            "enum": [
              "provisional",
              "final"
            ],
            "description": "Final after event-time window end plus5s watermark allowance"
          },
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "quality": {
            "enum": [
              "complete",
              "partial"
            ]
          }
        }
      },
      "TelemetrySnapshot": {
        "type": "object",
        "properties": {
          "farmId": {
            "$ref": "#/components/schemas/FarmId"
          },
          "assetId": {
            "type": "string"
          },
          "timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "current": {
            "type": "object",
            "properties": {
              "power": {
                "type": "number",
                "description": "MW"
              },
              "voltage": {
                "type": "number",
                "description": "V"
              },
              "temperature": {
                "type": "number",
                "description": "Celsius"
              },
              "windSpeed": {
                "type": "number",
                "description": "m/s"
              },
              "rotorSpeed": {
                "type": "number",
                "description": "rpm"
              },
              "frequency": {
                "type": "number",
                "description": "Hz"
              },
              "irradiance": {
                "type": "number",
                "description": "W/m²"
              },
              "efficiency": {
                "type": "number",
                "description": "percent"
              }
            }
          },
          "history": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/HistoryPoint"
            }
          },
          "derived": {
            "$ref": "#/components/schemas/DerivedWindow"
          },
          "previousWindows": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DerivedWindow"
            }
          },
          "channels": {
            "type": "array",
            "minItems": 50,
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/Signal"
            }
          },
          "controlState": {
            "enum": [
              "running",
              "curtailed",
              "maintenance"
            ]
          },
          "storage": {
            "$ref": "#/components/schemas/Storage"
          },
          "ingestedSignals": {
            "type": "integer"
          },
          "latencyMs": {
            "type": "integer",
            "description": "Server snapshot processing latency, not device-to-screen end-to-end latency"
          },
          "scheduleEnabled": {
            "type": "boolean",
            "description": "True only when a cron secret and durable Neon storage are configured."
          }
        }
      },
      "ControlCommand": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "farmId": {
            "$ref": "#/components/schemas/FarmId"
          },
          "assetId": {
            "type": "string"
          },
          "action": {
            "enum": [
              "curtail",
              "resume",
              "maintenance"
            ]
          },
          "state": {
            "enum": [
              "running",
              "curtailed",
              "maintenance"
            ]
          },
          "status": {
            "const": "acknowledged"
          },
          "requestedAt": {
            "type": "string",
            "format": "date-time"
          },
          "acknowledgedAt": {
            "type": "string",
            "format": "date-time"
          },
          "idempotencyKey": {
            "type": "string"
          }
        }
      },
      "Report": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "farmId": {
            "$ref": "#/components/schemas/FarmId"
          },
          "farmName": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "periodStart": {
            "type": "string",
            "format": "date-time"
          },
          "periodEnd": {
            "type": "string",
            "format": "date-time"
          },
          "status": {
            "const": "completed"
          },
          "trigger": {
            "enum": [
              "manual",
              "scheduled"
            ]
          },
          "windowCount": {
            "type": "integer"
          },
          "assetCount": {
            "type": "integer",
            "description": "Number of assets represented in the analyzed finalized windows; not the entire farm."
          },
          "statistics": {
            "type": "object",
            "properties": {
              "meanVoltageRange": {
                "type": "number"
              },
              "maxVoltageRange": {
                "type": "number"
              },
              "meanWindowMidpoint": {
                "type": "number"
              },
              "anomalyCount": {
                "type": "integer"
              },
              "forecastVoltageRange": {
                "type": "number",
                "description": "Exponential smoothing alpha=0.3 over chronological UTC-minute mean voltage ranges across assets observed in each minute. Missing minutes are skipped, not filled with zero. A baseline forecast for observed assets, not a trained ML forecast for the whole farm."
              },
              "observedWindowCompleteness": {
                "type": "number",
                "description": "Percent of expected 1 Hz samples within windows that exist. Excludes entirely missing windows; not an uptime or end-to-end coverage measure."
              },
              "observedAssetMinutes": {
                "type": "number",
                "description": "Sample-equivalent observed asset-minutes: sum of valid voltage sample counts, capped at 60 per window, divided by 60. Partial windows contribute fractional minutes."
              },
              "expectedAssetMinutes": {
                "type": "number",
                "description": "Full covered interval [earliest windowStart, latest windowEnd) in minutes times the number of observed assets; includes missing minutes."
              },
              "coveragePercent": {
                "type": "number",
                "description": "100 * observedAssetMinutes / expectedAssetMinutes. Includes missing minutes and partial windows for the observed asset cohort."
              },
              "expectedFarmAssetMinutes": {
                "type": "number",
                "description": "Full covered interval in minutes times all registered farm assets, including assets not selected for on-demand demo ingestion."
              },
              "farmCoveragePercent": {
                "type": "number",
                "description": "100 * observedAssetMinutes / expectedFarmAssetMinutes. Whole-farm sample coverage, including unobserved assets."
              }
            }
          },
          "findings": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "email": {
            "type": "object",
            "properties": {
              "to": {
                "type": "string"
              },
              "from": {
                "type": "string"
              },
              "subject": {
                "type": "string"
              },
              "html": {
                "type": "string"
              },
              "text": {
                "type": "string"
              }
            }
          },
          "storage": {
            "$ref": "#/components/schemas/Storage"
          },
          "farmAssetCount": {
            "type": "integer",
            "description": "Total assets registered in this demonstration farm."
          }
        }
      }
    }
  }
}
