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 ;}
function Notice({children,warning=false}) {return
{children}
;}
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
{!models.length&&No selected model produced a forecast for this series.}
{(item.failures||[]).map((failure,i)=>{MODEL_NAMES[failure.model]||failure.model}: {failure.reason})}
{predictions.length>0&&
Forecast starts {month(predictions[0].timestamp)}. These are point estimates; calibrated uncertainty intervals are not available.
}
Monthly predictions and model diagnostics
Month
{models.map(([name])=>
{MODEL_NAMES[name]||name} · {unit}
)}
{predictions.map((p,i)=>
{month(p.timestamp)}
{models.map(([name,m])=>
{number(m.predictions[i]?.value)}
)}
)}
{item.warnings?.length>0&&
Model warnings: {item.warnings.join(', ')}
};
}
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
{stale&&news.status!=='stale'&&Showing an older news snapshot. Its publication and retrieval dates remain visible below.}
{unavailable[news.status]&&{unavailable[news.status]} Your numerical analysis does not depend on news availability.}
{articles.length>0&&
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.
}
Grid demand and wholesale prices describe the market. Household bills use the customer's consumption and retail contract.
}
{data.excluded_offers?.length>0&&Excluded offers and reasons ({data.excluded_offers.length}){data.excluded_offers.map((offer,i)=>
{offer.offer_id}: {offer.reason}
)}}
This compares supplied offers, subject to their terms. Future rates and realized savings remain uncertain.
;
}
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
Analysis runs when you request it{latest?`Latest complete month: ${latest}`:'Each source keeps its own publication date'}Private results expire after one hour
{runtimeError&&Service readiness could not be checked. You can retry the analysis; its response will show any connection error.}
{role==='customer'?'Start with your consumption':'Bring the series you want to examine'}
{role==='customer'?'A monthly CSV gives your forecast its own history.':'Up to ten anonymous consumption or price series per run.'}
01
{rows&&}
{rows&&<>{normalized.error?
{normalized.error}
:
{normalized.series.map(series=>
{series.series_id}{series.records.length} months · {month(series.records[0].timestamp)} to {month(series.records.at(-1).timestamp)} · {series.records[0].unit}
)}
}>}
{role==='ngo'&&}
{!rows&&
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.
}
{role==='customer'&&Compare provider quotes with your annual usage
Enter your own totals and upload complete, dated offers. This is a first-year cost scenario; it does not require a forecast.