Spaces:
Running

File size: 34,881 Bytes
684a9cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afb6251
684a9cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce65d97
684a9cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afb6251
684a9cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import React, {useEffect, useMemo, useRef, useState} from 'react';
import {Activity, AlertCircle, ArrowRight, ArrowUpRight, CheckCircle2, Clock3, Download, FileSpreadsheet, Home, Info, Newspaper, RefreshCw, Upload, Users, Zap} from 'lucide-react';
import Papa from 'papaparse';

const MODEL_NAMES = {seasonal_naive:'Seasonal baseline', sarima:'SARIMA', grokked_sarima:'Grokked SARIMA', sarimax_garch:'Calendar SARIMAX + GARCH'};
const COLORS = ['#16856b', '#416db7', '#b77b27', '#8c5cad'];
const UNITS = new Set(['kWh','GWh','EUR/kWh','AUD/kWh','EUR/MWh','AUD/MWh']);
const number = value => Number(value).toLocaleString(undefined,{maximumFractionDigits:2});
const month = value => String(value || '').slice(0,7);
const safeURL = value => {try {const url=new URL(value); return ['https:','http:'].includes(url.protocol)?url.href:null;} catch {return null;}};
function dated(value) {if(!value)return 'Not supplied'; const date=new Date(value);return Number.isNaN(date.valueOf())?'Not supplied':date.toLocaleString(undefined,{dateStyle:'medium',timeStyle:'short'});}
function noteText(value) {return typeof value==='string'?value:value?.message||value?.reason||JSON.stringify(value);}
function Field({label,children}) {return <label className="field"><span>{label}</span>{children}</label>;}
function Notice({children,warning=false}) {return <div className={`live-note${warning?' warning':''}`}><Info size={17}/><div>{children}</div></div>;}

async function call(path, payload, signal) {
  const bounded=new AbortController();let timedOut=false;
  const cancel=()=>bounded.abort();
  signal?.addEventListener('abort',cancel,{once:true});
  if(signal?.aborted)bounded.abort();
  const timeout=setTimeout(()=>{timedOut=true;bounded.abort();},45000);
  try {
    const response=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:bounded.signal});
    const data=await response.json();
    if(!response.ok)throw Error(typeof data.detail==='string'?data.detail:'The request could not be completed. Review the inputs and try again.');
    return data;
  }catch(error){if(timedOut)throw Error('The service took too long to respond. Try checking the request again.');throw error;}
  finally {clearTimeout(timeout);signal?.removeEventListener('abort',cancel);}
}

function readCSV(file) {
  if(!file)return Promise.resolve(null);
  if(file.size>2_000_000)return Promise.reject(Error('Use a CSV smaller than 2 MB.'));
  return new Promise((resolve,reject)=>Papa.parse(file,{header:true,skipEmptyLines:'greedy',transformHeader:h=>h.replace(/^\uFEFF/,'').trim(),complete:result=>{
    if(result.errors.length)return reject(Error(`CSV: ${result.errors[0].message}`));
    if(!result.data.length)return reject(Error('This CSV has no data rows.'));
    resolve(result.data);
  },error:reject}));
}

// Coverage is never invented from an invoice allocation: the uploader must
// either supply coverage=1 or explicitly attest to complete measured months.
export function normalizeSeries(rows, role, completeMonths) {
  if(!rows?.length)return [];
  const grouped=new Map();
  for(const [index,row] of rows.entries()) {
    const allocation=String(row.allocation||'').toLowerCase();
    if(/uniform|pro-rated|prorated|estimate/.test(allocation))throw Error(`Row ${index+2}: allocated or estimated invoice months cannot be used as measured forecast observations.`);
    const sid=String(row.series_id|| (role==='customer'?'anonymous-meter':'anonymous-series')).trim();
    if(!sid||sid.length>100)throw Error(`Row ${index+2}: use an anonymous series_id of 1–100 characters.`);
    const isBill=Object.hasOwn(row,'month')&&Object.hasOwn(row,'kwh');
    const stamp=isBill&&/^\d{4}-\d{2}$/.test(String(row.month).trim())?`${String(row.month).trim()}-01`:String(row.timestamp||'').trim();
    const rawValue=isBill?row.kwh:row.value;
    const value=Number(rawValue);
    const unit=isBill?'kWh':String(row.unit||'').trim();
    const suppliedCoverage=row.coverage!==undefined&&String(row.coverage).trim()!=='';
    if((!suppliedCoverage||isBill)&&!completeMonths)throw Error('Confirm that the uploaded rows represent complete, measured monthly usage. Allocated PDF months cannot be used as measured forecast observations.');
    const coverage=suppliedCoverage?Number(row.coverage):1;
    if(!/^\d{4}-\d{2}-01(?:T00:00:00(?:\.0+)?)?$/.test(stamp))throw Error(`Row ${index+2}: use a month-start timestamp (YYYY-MM-01), or month and kwh columns.`);
    if(String(rawValue??'').trim()===''||!Number.isFinite(value)||!UNITS.has(unit)||coverage!==1)throw Error(`Row ${index+2}: supply a finite value, a supported electricity unit, and complete coverage=1.`);
    if(!grouped.has(sid))grouped.set(sid,[]);
    grouped.get(sid).push({timestamp:stamp.slice(0,10),value,unit,coverage});
  }
  if(grouped.size>(role==='customer'?1:10))throw Error(role==='customer'?'Customer mode accepts one meter at a time. Use NGO mode for multiple named series.':'NGO mode accepts up to ten named series per run.');
  const now=new Date();
  const currentMonth=now.getUTCFullYear()*12+now.getUTCMonth();
  return [...grouped].map(([series_id,records])=>{
    records.sort((a,b)=>a.timestamp.localeCompare(b.timestamp));
    if(records.length<12||records.length>600)throw Error(`${series_id}: upload 12–600 complete months. A shorter billing snapshot can still be reviewed under Import bills & swaps.`);
    if(new Set(records.map(r=>r.unit)).size!==1)throw Error(`${series_id}: keep usage, retail price and wholesale price in separate series.`);
    let previous;
    for(const record of records) {
      const [year,monthNumber]=record.timestamp.split('-').map(Number);
      const serial=year*12+monthNumber-1;
      if(monthNumber<1||monthNumber>12||year<1900||serial>=currentMonth)throw Error(`${series_id}: forecast inputs must be complete past months.`);
      if(previous!==undefined&&serial!==previous+1)throw Error(`${series_id}: months must be consecutive, without duplicates or gaps.`);
      if(!record.unit.endsWith('/MWh')&&record.value<0)throw Error(`${series_id}: only wholesale prices may contain negative values.`);
      previous=serial;
    }
    return {series_id,records};
  });
}

function csvTemplate(role) {
  const header=role==='ngo'?'series_id,timestamp,value,unit,coverage\n':'month,kwh\n';
  const url=URL.createObjectURL(new Blob([header],{type:'text/csv;charset=utf-8'}));
  const anchor=document.createElement('a');anchor.href=url;anchor.download=`electrocheap-${role}-empty-template.csv`;anchor.click();URL.revokeObjectURL(url);
}

function ForecastChart({history, models}) {
  const entries=Object.entries(models||{}).filter(([,m])=>m.predictions?.length);
  const actual=(history||[]).slice(-12);
  if(!entries.length)return null;
  const all=[...actual.map(r=>r.value),...entries.flatMap(([,m])=>m.predictions.map(p=>p.value))];
  const low=Math.min(...all), high=Math.max(...all), padding=(high-low)*.15||1;
  const n=Math.max(actual.length+entries[0][1].predictions.length,2), width=720,height=226,left=57,right=16,top=18,bottom=38;
  const x=i=>left+i*(width-left-right)/(n-1);
  const y=value=>height-bottom-(value-low+padding)/(high-low+2*padding)*(height-top-bottom);
  const origin=actual.length-1;
  const labels=[...actual.map(r=>r.timestamp),...entries[0][1].predictions.map(p=>p.timestamp)];
  return <div className="live-forecast-chart"><svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="Monthly observations followed by forecasts; dashed lines are predictions">
    {[0,1,2].map(i=>{const v=high+padding-i*(high-low+2*padding)/2;return <g key={i}><line x1={left} x2={width-right} y1={y(v)} y2={y(v)} stroke="#e2ebe6"/><text x={left-9} y={y(v)+4} textAnchor="end">{number(v)}</text></g>;})}
    {actual.length>0&&<><polyline points={actual.map((r,i)=>`${x(i)},${y(r.value)}`).join(' ')} fill="none" stroke="#334e46" strokeWidth="2.4"/><line x1={x(origin)} x2={x(origin)} y1={top} y2={height-bottom} stroke="#9cb4a8" strokeDasharray="3 4"/></>}
    {entries.map(([name,model],k)=>{const points=[...(actual.length?[`${x(origin)},${y(actual.at(-1).value)}`]:[]),...model.predictions.map((r,i)=>`${x(actual.length+i)},${y(r.value)}`)];return <polyline key={name} points={points.join(' ')} fill="none" stroke={COLORS[k%COLORS.length]} strokeWidth="2.5" strokeDasharray="6 4"/>;})}
    {[0,...(origin>0?[origin]:[]),n-1].filter((v,i,a)=>a.indexOf(v)===i).map(i=><text key={i} x={x(i)} y={height-12} textAnchor={i===0?'start':i===n-1?'end':'middle'}>{month(labels[i])}</text>)}
  </svg><div className="live-legend">{actual.length>0&&<span><i style={{background:'#334e46'}}/>Measured history</span>}{entries.map(([name],k)=><span key={name}><i style={{background:COLORS[k%COLORS.length]}}/>{MODEL_NAMES[name]||name}</span>)}</div></div>;
}

function SeriesResult({item,input}) {
  const models=Object.entries(item.models||{}), predictions=models[0]?.[1]?.predictions||[];
  const unit=models[0]?.[1]?.unit||input?.records?.[0]?.unit||'';
  const quantity=['kWh','GWh'].includes(unit);
  const total=predictions.reduce((sum,p)=>sum+p.value,0);
  return <section className="panel live-series"><div className="live-result-heading"><div><span className="live-kicker">FRESH FORECAST</span><h3>{item.series_id}</h3><p>{item.observations} observations · last actual {month(item.origin)}</p></div>{predictions.length>0&&<div className="live-result-number"><small>{quantity?'Forecast total':'Mean forecast price'} · {predictions.length} months</small><strong>{number(quantity?total:total/predictions.length)} <span>{unit}</span></strong><small>{MODEL_NAMES[models[0][0]]||models[0][0]}</small></div>}</div>
    <ForecastChart history={input?.records} models={item.models}/>
    {!models.length&&<Notice warning>No selected model produced a forecast for this series.</Notice>}
    {(item.failures||[]).map((failure,i)=><Notice warning key={i}>{MODEL_NAMES[failure.model]||failure.model}: {failure.reason}</Notice>)}
    {predictions.length>0&&<p className="live-caption">Forecast starts {month(predictions[0].timestamp)}. These are point estimates; calibrated uncertainty intervals are not available.</p>}
    <details><summary>Monthly predictions and model diagnostics</summary><div className="table-wrap"><table><thead><tr><th>Month</th>{models.map(([name])=><th key={name}>{MODEL_NAMES[name]||name} · {unit}</th>)}</tr></thead><tbody>{predictions.map((p,i)=><tr key={p.timestamp}><td>{month(p.timestamp)}</td>{models.map(([name,m])=><td key={name}>{number(m.predictions[i]?.value)}</td>)}</tr>)}</tbody></table></div>{item.warnings?.length>0&&<p className="live-caption">Model warnings: {item.warnings.join(', ')}</p>}</details>
  </section>;
}

function NewsResult({news}) {
  if(!news||['skipped','not_requested'].includes(news.status))return null;
  const articles=news.articles||[];
  const stale=news.stale===true||news.status==='stale';
  const unavailable={not_configured:'Market news is not connected.',unconfigured:'Market news is not connected.',quota_exhausted:'The news search allowance has been reached.',unavailable:'The news source is temporarily unavailable.',empty:'No matching articles were returned.',stale:'Showing an older news snapshot.'};
  return <section className="panel live-news"><div className="section-title"><span className="icon-box"><Newspaper size={19}/></span><div><h2>What is changing in the market</h2><p>SerpApi · Google News · sourced context</p></div><span className="live-badge">{stale?'Older snapshot':news.cache_hit?'Cached':articles.length?'Retrieved':String(news.status||'unavailable').replaceAll('_',' ')}</span></div>
    {stale&&news.status!=='stale'&&<Notice warning>Showing an older news snapshot. Its publication and retrieval dates remain visible below.</Notice>}
    {unavailable[news.status]&&<Notice warning={!['empty'].includes(news.status)}>{unavailable[news.status]} Your numerical analysis does not depend on news availability.</Notice>}
    {articles.length>0&&<div className="live-news-list">{articles.slice(0,10).map((article,i)=>{const href=safeURL(article.url||article.link);return <article key={`${href}-${i}`}><div><span>{typeof article.source==='object'?article.source?.name:article.source||'Source not supplied'}</span><time>{article.published_at?dated(article.published_at):'Publication date unavailable'}</time></div><h3>{href?<a href={href} target="_blank" rel="noreferrer noopener">{article.title}<ArrowUpRight size={15}/></a>:article.title}</h3></article>;})}</div>}
    <p className="live-caption">Retrieved: {dated(news.fetched_at||news.retrieved_at)}{news.cache_expires_at?` · Cache valid until ${dated(news.cache_expires_at)}`:''}</p><p className="live-caption">Headlines provide context. A rate change enters a bill comparison only through a dated, complete tariff quote.</p>
  </section>;
}

function MarketResult({market,country}) {
  if(!market||['skipped','not_requested'].includes(market.status))return null;
  const meta=market.metadata||{}, records=market.records||[];
  const urls=[...(meta.source_urls||[]),...(meta.source_url?[meta.source_url]:[])].filter(safeURL);
  const columns=Object.keys(records[0]||{}).slice(0,6);
  return <section className="panel live-market"><div className="section-title"><span className="icon-box"><Activity size={19}/></span><div><h2>Official market context</h2><p>{country==='PT'?'REN · Portugal':country==='DE'?'SMARD · Germany':'AEMO · Australia'}</p></div><span className="live-badge">{String(market.status||'unknown').replaceAll('_',' ')}</span></div>
    <div className="live-source-facts"><div><span>Covered month</span><strong>{meta.month||market.month||'See source records'}</strong></div><div><span>Retrieved</span><strong>{dated(meta.retrieved_at||market.retrieved_at)}</strong></div><div><span>Source records</span><strong>{Number(meta.rows_total??records.length).toLocaleString()} total · {records.length.toLocaleString()} in preview</strong></div></div>
    {market.error||market.message?<Notice warning>{market.message||market.error}</Notice>:null}
    {meta.scope&&<p className="live-caption">{meta.scope}</p>}
    {meta.null_policy&&<p className="live-caption">{meta.null_policy}</p>}
    {urls.length>0&&<div className="live-source-links">{urls.map((url,i)=><a href={url} target="_blank" rel="noreferrer noopener" key={url}>Official source {urls.length>1?i+1:''}<ArrowUpRight size={13}/></a>)}</div>}
    {records.length>0&&<details><summary>Inspect latest source records</summary><div className="table-wrap"><table><thead><tr>{columns.map(c=><th key={c}>{c.replaceAll('_',' ')}</th>)}</tr></thead><tbody>{records.slice(-10).map((record,i)=><tr key={i}>{columns.map(c=><td key={c}>{typeof record[c]==='number'?number(record[c]):String(record[c]??'Missing')}</td>)}</tr>)}</tbody></table></div><p className="live-caption">Showing the last {Math.min(records.length,10)} preview records. The audit contains a bounded preview of {records.length} of {Number(meta.rows_total??records.length).toLocaleString()} publisher records, with the full publisher source URLs.</p></details>}
    <p className="live-caption">Grid demand and wholesale prices describe the market. Household bills use the customer's consumption and retail contract.</p>
  </section>;
}

function ComparisonResult({comparison,currency}) {
  if(!comparison)return null;
  const data=comparison.result||comparison;
  const rows=data.ranked_offers||[];
  if(comparison.error)return <section className="panel"><h2>Quote comparison</h2><Notice warning>{comparison.error}</Notice></section>;
  return <section className="panel"><div className="section-title"><div><span className="live-kicker">SUPPLIED OFFER COMPARISON</span><h2>{rows.length?`${rows[0].provider} has the lowest supplied first-year cost`:'No eligible supplied offers'}</h2><p>Annual usage scenario · tax-inclusive quotes · {currency}</p></div></div>
    {rows.length>0&&<div className="table-wrap"><table><thead><tr><th>Provider</th><th>First-year cost · {currency}</th><th>Difference from current bill · {currency}</th></tr></thead><tbody>{rows.map((row,i)=><tr key={row.offer_id||i}><td>{row.provider}</td><td>{number(row.first_year_cost)}</td><td>{number(row.estimated_saving)}</td></tr>)}</tbody></table></div>}
    {data.excluded_offers?.length>0&&<details><summary>Excluded offers and reasons ({data.excluded_offers.length})</summary>{data.excluded_offers.map((offer,i)=><p className="live-caption" key={i}>{offer.offer_id}: {offer.reason}</p>)}</details>}
    <p className="live-caption">This compares supplied offers, subject to their terms. Future rates and realized savings remain uncertain.</p>
  </section>;
}

export default function LiveWorkspace({country,market,runtime,runtimeError,onOpenBills,onPendingChange}) {
  const [role,setRole]=useState('customer'),[rows,setRows]=useState(null),[filename,setFilename]=useState(''),[complete,setComplete]=useState(false),[official,setOfficial]=useState(false);
  const [horizon,setHorizon]=useState(12),[models,setModels]=useState(['seasonal_naive']);
  const [includeNews,setIncludeNews]=useState(false),[includeMarket,setIncludeMarket]=useState(true),[region,setRegion]=useState(market.region);
  const [annual,setAnnual]=useState(''),[annualCost,setAnnualCost]=useState(''),[power,setPower]=useState(''),[meter,setMeter]=useState('standard'),[peak,setPeak]=useState('');
  const [offers,setOffers]=useState(null),[offerName,setOfferName]=useState(''),[accepted,setAccepted]=useState('');
  const [error,setError]=useState(''),[submitting,setSubmitting]=useState(false),[job,setJob]=useState(null),[result,setResult]=useState(null),[submitted,setSubmitted]=useState(null),[pollVersion,setPollVersion]=useState(0);
  const controller=useRef(null), resultsRef=useRef(null), fileVersion=useRef(0);
  const pending=submitting||['queued','running'].includes(job?.state);
  const normalized=useMemo(()=>{try{return {series:normalizeSeries(rows,role,complete),error:null}}catch(e){return {series:[],error:e.message}}},[rows,role,complete]);
  const useOfficial=role==='ngo'&&official&&!rows?.length;
  const minimum=useOfficial?36:normalized.series.length?Math.min(...normalized.series.map(s=>s.records.length)):0;
  const hasProfile=annual!==''||annualCost!=='';
  const hasNumeric=!!rows?.length||hasProfile||useOfficial;
  const latest=runtime?.latest_complete_month||runtime?.latest_month;

  useEffect(()=>{onPendingChange?.(pending);return()=>onPendingChange?.(false);},[pending,onPendingChange]);

  useEffect(()=>()=>{controller.current?.abort();fileVersion.current+=1;},[]);
  useEffect(()=>{if(minimum<36)setModels(['seasonal_naive']);},[minimum]);
  useEffect(()=>{
    if(!job?.job_id||!['queued','running'].includes(job.state))return;
    let cancelled=false,timer,attempts=0;
    const aborter=new AbortController();
    const poll=async()=>{
      try {
        const next=await call('/api/analysis_result',{job_id:job.job_id,limit:100},aborter.signal);
        if(cancelled)return;
        if(next.state==='completed'){setJob(next);setResult(next.result);requestAnimationFrame(()=>resultsRef.current?.scrollIntoView({behavior:'smooth',block:'start'}));return;}
        if(next.state==='failed'){setJob(next);setError(next.error||'The analysis failed. No completed result is being claimed.');return;}
        setJob(previous=>({...previous,state:next.state}));
        attempts+=1;
        if(attempts>=180){setJob(previous=>({...previous,state:'paused'}));setError('The analysis is taking longer than expected. Use Check job to resume status checks; it will not submit a second run.');return;}
        timer=setTimeout(poll,2500);
      }catch(e){if(!cancelled&&e.name!=='AbortError'){setJob(previous=>({...previous,state:'paused'}));setError('Could not read the job status. Use Check job to reconnect to the existing run.');}}
    };
    timer=setTimeout(poll,900);
    return()=>{cancelled=true;clearTimeout(timer);aborter.abort();};
  },[job?.job_id,pollVersion]);

  const changeRole=next=>{if(pending||next===role)return;setRole(next);setOfficial(next==='ngo');setRows(null);setFilename('');setComplete(false);setOffers(null);setOfferName('');setAnnual('');setAnnualCost('');setError('');setJob(null);setResult(null);setSubmitted(null);fileVersion.current+=1;};
  const upload=async(file,type)=>{
    if(!file)return;
    const version=++fileVersion.current;setError('');
    try {const data=await readCSV(file);if(fileVersion.current!==version)return;
      if(type==='series'){setRows(data);setOfficial(false);setFilename(file.name);setComplete(false);setModels(['seasonal_naive']);}
      else {if(data.length>500)throw Error('Supply at most 500 offers.');setOffers(data);setOfferName(file.name);}
      setResult(null);setJob(null);
    }catch(e){if(fileVersion.current===version)setError(e.message);}
  };
  const submit=async()=>{
    setError('');
    if(normalized.error){setError(normalized.error);return;}
    if(rows?.length&&!complete){setError('Confirm that the uploaded rows are complete, measured observations before running inference.');return;}
    if(!normalized.series.length&&!hasProfile&&!useOfficial&&!includeNews&&!includeMarket){setError('Add data, or select market news or the official feed for a market brief.');return;}
    if((normalized.series.length||useOfficial)&&!models.length){setError('Select at least one forecast model.');return;}
    if(hasProfile&&(!annual||annualCost===''||Number(annual)<=0||Number(annualCost)<0)){setError('Supply positive annual usage and the full current electricity cost.');return;}
    if((hasProfile&&!offers?.length)||(offers?.length&&!hasProfile)){setError('An offer comparison needs both annual consumption/current cost and complete provider quotes.');return;}
    if(hasProfile&&meter==='smart'&&(peak===''||Number(peak)<0||Number(peak)>100)){setError('Supply the measured peak-use percentage for the smart-meter quote comparison.');return;}
    const payload={role,country,region,horizon_months:Number(horizon),models,series:normalized.series,include_news:includeNews,include_market:includeMarket,use_official_history:useOfficial,observations_are_measured:!!rows?.length&&complete};
    if(hasProfile){payload.profile={country,region,annual_kwh:Number(annual),current_annual_bill:Number(annualCost),meter_type:meter,profile_source:'annual_user_input',customer_type:'consumer'};if(power!=='')payload.profile.contracted_power_kva=Number(power);if(meter==='smart')payload.profile.peak_share=Number(peak)/100;payload.offers=offers;payload.accepted_conditions=accepted.split(',').map(s=>s.trim()).filter(Boolean);}
    controller.current?.abort();controller.current=new AbortController();setSubmitting(true);setResult(null);setJob(null);
    try {const ticket=await call('/api/live_analysis',payload,controller.current.signal);setSubmitted(payload);setJob({...ticket,state:ticket.state||'queued'});}
    catch(e){if(e.name!=='AbortError')setError(e.message);}
    finally {setSubmitting(false);}
  };
  const resultSeries=result?.series?.length?result.series:result?.forecast?.series||[];
  const successful=resultSeries.reduce((count,s)=>count+Object.keys(s.models||{}).length,0);

  return <div className="live-workspace">
    <div className="live-mode-switch" aria-label="Analysis audience"><button type="button" aria-pressed={role==='customer'} className={role==='customer'?'selected':''} disabled={pending} onClick={()=>changeRole('customer')}><Home size={20}/><span><strong>For a customer</strong><small>One meter. Your costs and forecast.</small></span>{role==='customer'&&<CheckCircle2 size={17}/>}</button><button type="button" aria-pressed={role==='ngo'} className={role==='ngo'?'selected':''} disabled={pending} onClick={()=>changeRole('ngo')}><Users size={20}/><span><strong>For an NGO</strong><small>Compare series. Examine market changes.</small></span>{role==='ngo'&&<CheckCircle2 size={17}/>}</button></div>
    <div className="live-freshness"><span><Clock3 size={15}/> Analysis runs when you request it</span><span>{latest?`Latest complete month: ${latest}`:'Each source keeps its own publication date'}</span><span>Private results expire after one hour</span></div>
    {runtimeError&&<Notice warning>Service readiness could not be checked. You can retry the analysis; its response will show any connection error.</Notice>}
    <div className="live-columns"><section className="panel live-input-panel"><div className="section-title"><span className="icon-box"><Upload size={19}/></span><div><h2>{role==='customer'?'Start with your consumption':'Bring the series you want to examine'}</h2><p>{role==='customer'?'A monthly CSV gives your forecast its own history.':'Up to ten anonymous consumption or price series per run.'}</p></div><span className="step">01</span></div>
      <label className="live-upload"><FileSpreadsheet size={29}/><strong>{filename||'Add monthly electricity data'}</strong><span>{filename?`${rows.length.toLocaleString()} rows read · ready for review`:role==='customer'?'CSV · month + kwh, or normalized monthly records':'CSV · series_id, timestamp, value, unit, coverage'}</span><input aria-label="Upload monthly electricity data" type="file" accept=".csv,text/csv" disabled={pending} onChange={e=>{const file=e.target.files?.[0];e.target.value='';upload(file,'series');}}/></label>
      <div className="live-upload-actions"><button type="button" onClick={()=>csvTemplate(role)}><Download size={13}/>Empty CSV template</button><button type="button" onClick={onOpenBills}>Have ZIP / PDF bills?<ArrowRight size={13}/></button>{rows&&<button type="button" disabled={pending} onClick={()=>{setRows(null);setFilename('');setComplete(false);}}>Clear</button>}</div>
      {rows&&<><label className="live-check"><input type="checkbox" checked={complete} disabled={pending} onChange={e=>setComplete(e.target.checked)}/><span>These are complete, measured monthly observations.<small>Daily allocations from PDF bills and partial months are not measured monthly actuals.</small></span></label>{normalized.error?<p className="live-validation"><AlertCircle size={14}/>{normalized.error}</p>:<div className="live-data-summary">{normalized.series.map(series=><div key={series.series_id}><CheckCircle2 size={14}/><b>{series.series_id}</b><span>{series.records.length} months · {month(series.records[0].timestamp)} to {month(series.records.at(-1).timestamp)} · {series.records[0].unit}</span></div>)}</div>}</>}
      {role==='ngo'&&<label className="live-check live-official-choice"><input type="checkbox" checked={official} disabled={pending||!!rows?.length} onChange={e=>setOfficial(e.target.checked)}/><Activity size={17}/><span>Use official grid history<small>Refresh the latest complete month, then fit a new grid-demand forecast in GWh. {country==='AU'?'This uses the NEM-wide history; regional context remains separate.':'This forecasts the whole grid, not individual household usage.'}</small></span></label>}
      {!rows&&<p className="live-input-help">Use at least 12 consecutive measured months for a seasonal baseline, or 36 for statistical models. You can also run a market brief without personal data.</p>}
      {role==='customer'&&<details className="live-offer-options"><summary>Compare provider quotes with your annual usage</summary><p className="live-caption">Enter your own totals and upload complete, dated offers. This is a first-year cost scenario; it does not require a forecast.</p><div className="form-grid"><Field label="Annual consumption · kWh"><input type="number" min="0.01" step="any" value={annual} disabled={pending} onChange={e=>setAnnual(e.target.value)} placeholder="Your annual usage"/></Field><Field label={`Annual electricity cost · ${market.currency}`}><input type="number" min="0" step="any" value={annualCost} disabled={pending} onChange={e=>setAnnualCost(e.target.value)} placeholder="Tax included"/></Field><Field label="Contracted power · kVA (if applicable)"><input type="number" min="0.1" step="any" value={power} disabled={pending} onChange={e=>setPower(e.target.value)}/></Field><Field label="Meter"><select value={meter} disabled={pending} onChange={e=>setMeter(e.target.value)}><option value="standard">Standard</option><option value="smart">Smart / time of use</option></select></Field></div>{meter==='smart'&&<Field label="Measured peak usage · %"><input type="number" min="0" max="100" step="any" value={peak} disabled={pending} onChange={e=>setPeak(e.target.value)}/></Field>}<label className="live-quote-upload"><Upload size={16}/>{offerName||'Add complete provider quotes · CSV'}<input aria-label="Upload provider quotes" type="file" accept=".csv" disabled={pending} onChange={e=>{const file=e.target.files?.[0];e.target.value='';upload(file,'offers');}}/></label><a className="live-template-link" href="/downloads/quote_template.csv" download>Offer template<Download size={12}/></a><Field label="Offer conditions you have accepted · IDs, comma separated"><input value={accepted} disabled={pending} onChange={e=>setAccepted(e.target.value)}/></Field></details>}
    </section>
    <section className="panel live-run-panel"><div className="section-title"><span className="icon-box"><Zap size={19}/></span><div><h2>Choose what to run</h2><p>New calculations with dated source context.</p></div><span className="step">02</span></div><div className="form-grid"><Field label="Forecast horizon"><select value={horizon} disabled={pending} onChange={e=>setHorizon(e.target.value)}>{[3,12,24,36].map(h=><option key={h} value={h}>{h} months</option>)}</select></Field><Field label={country==='AU'?'NEM region':'Eligibility region / grid'}>{country==='AU'?<select value={region} disabled={pending} onChange={e=>setRegion(e.target.value)}>{['NSW1','QLD1','SA1','TAS1','VIC1'].map(r=><option key={r}>{r}</option>)}</select>:<input value={region} disabled={pending} onChange={e=>setRegion(e.target.value)}/>}</Field></div>
      <div className="live-options"><label className="live-check"><input type="checkbox" checked={includeMarket} disabled={pending} onChange={e=>setIncludeMarket(e.target.checked)}/><Activity size={17}/><span>Fetch official market data<small>{country==='PT'?'REN':country==='DE'?'SMARD':'AEMO'} · latest complete month, with coverage</small></span></label><label className="live-check"><input type="checkbox" checked={includeNews} disabled={pending||runtime?.news?.configured!==true} onChange={e=>setIncludeNews(e.target.checked)}/><Newspaper size={17}/><span>Include electricity news<small>{runtime?.news?.configured?'SerpApi / Google News · public market context':'Not connected · server-side SerpApi setup required'}</small></span></label></div>
      <details className="live-model-options"><summary>Forecast models <span>{models.length} selected</span></summary>{Object.entries(MODEL_NAMES).map(([name,label])=><label className="live-check" key={name}><input type="checkbox" checked={models.includes(name)} disabled={pending||(name!=='seasonal_naive'&&minimum<36)} onChange={e=>setModels(previous=>e.target.checked?[...previous,name]:previous.filter(value=>value!==name))}/><span>{label}<small>{name==='seasonal_naive'?'12 complete months':name==='grokked_sarima'?'36 months · 80% SARIMA + 20% seasonal template':name==='sarimax_garch'?'36 months · calendar features + residual variance':'36 complete months'}</small></span></label>)}<p className="live-caption">Model failures are reported separately. News does not silently alter model inputs or tariff prices.</p></details>
      {!hasNumeric&&<div className="live-brief-note"><Newspaper size={18}/><div><b>Market brief only</b><span>Add monthly data to calculate a forecast, or annual usage and quotes to compare offers.</span></div></div>}
      {error&&<div className="live-error" role="alert"><AlertCircle size={17}/><span>{error}</span></div>}
      <button className="primary full live-submit" type="button" disabled={pending||job?.state==='paused'} onClick={submit}>{pending?<RefreshCw size={17} className="live-spinning"/>:<Zap size={17}/>}<span>{submitting?'Submitting your request…':pending?'Analysis in progress…':hasNumeric?'Run analysis now':'Run market brief'}</span><ArrowRight size={17}/></button>
      {job&&<div className={`live-job ${job.state==='failed'?'failed':''}`} role="status" aria-live="polite"><span>{job.state==='completed'?<CheckCircle2 size={16}/>:<Clock3 size={16}/>} {job.state==='completed'?'Analysis completed':job.state==='queued'?'Queued for calculation':job.state==='running'?'Calculating and collecting sources':job.state==='paused'?'Status checks paused':'Analysis failed'}</span>{job.state==='paused'&&<button onClick={()=>{setError('');setJob(previous=>({...previous,state:'running'}));setPollVersion(v=>v+1);}}>Check job<RefreshCw size={13}/></button>}</div>}
      <p className="live-private-note">Use anonymous data. Results and audit links expire after one hour or a restart. Public news queries never include your billing data.</p>
    </section></div>
    {!result&&<div className="live-expectations"><div><Activity size={18}/><span><b>Calculated for this request</b><small>{useOfficial?'Forecast the refreshed official grid series.':'Forecasts use the series you supply.'}</small></span></div><div><Clock3 size={18}/><span><b>Dates stay visible</b><small>Actuals, forecasts and news have distinct dates.</small></span></div><div><Download size={18}/><span><b>Evidence you can inspect</b><small>Download inputs, results and provenance.</small></span></div></div>}
    {result&&<div className="live-results" ref={resultsRef}><div className="live-results-header"><div><span className="live-kicker">THIS REQUEST</span><h2>{successful?`${successful} forecast${successful===1?'':'s'} calculated`:result.inference_status==='failed'?'Forecast unavailable — inspect the diagnostics':result.comparison?'Your comparison and market context':'Your market brief'}</h2><p>{market.name} · {role==='ngo'?'NGO workspace':'Customer workspace'} · requested {dated(result.requested_at||job.created_at)}</p></div>{job.export_path&&<a className="secondary" href={job.export_path} download><Download size={16}/>Download private audit</a>}</div>
      {(result.warnings||[]).map((warning,i)=><Notice warning key={i}>{noteText(warning)}</Notice>)}
      {resultSeries.map(item=><SeriesResult key={item.series_id} item={item} input={submitted?.series.find(s=>s.series_id===item.series_id)||(submitted?.use_official_history?{records:result.official_history?.records}:null)}/>)}
      <ComparisonResult comparison={result.comparison} currency={market.currency}/>
      <div className="live-context-grid"><MarketResult market={result.market} country={country}/><NewsResult news={result.news}/></div>
      <details className="panel live-audit-details"><summary>Full result, input freshness and provenance</summary><pre className="json">{JSON.stringify(result,null,2)}</pre></details>
    </div>}
  </div>;
}