<?php
require_once __DIR__ . '/engine/engine.php';
require_once __DIR__ . '/engine/api-handling/fmp_client.php';

$requires_search = true;
$requires_chartjs = true;

$symbol = $_GET['symbol'] ?? $_POST['symbol'] ?? '';

require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';
?>
<main class="flex-grow-1">
	<div class="container pb-5">
		<div class="row">
			<div class="col-12">
				<div class="sticky-top mt-5 bg-white z-3 pb-3">
					<div class="d-flex justify-content-between align-items-center">
						<h1 class="mb-4">Forecast</h1>
					<div>
					<?php
						if ($symbol) {
						$category = 'Forecast';
						include 'execute/watchlist/watchlist_button.php';
						}
					?>
					</div>
				</div>

				<form id="fcForm" onsubmit="return false;">
					<div class="row g-3">
						<div class="col-md-4">
							<label for="symbol" class="form-label">Symbol eingeben</label>
							<input type="text" class="form-control symbol-autocomplete" name="symbol" id="symbol" placeholder="AAPL" value="<?= htmlspecialchars($symbol) ?>" required>
						</div>
		
						<div class="col-md-4">
							<label for="h" class="form-label">Horizont (Tage)</label>
							<select id="h" name="h" class="form-select">
								<option value="20">20</option>
								<option value="10">10</option>
								<option value="40">40</option>
							</select>
						</div>
						
						<div class="col-md-4">
						  <label for="atr" class="form-label">ATR-Multiplikator</label>
						  <input type="number" id="atr" name="atr" class="form-control" step="0.1" value="1.5">
						</div>
						
						<div class="col-12">
							<button type="button" id="runBtn" class="btn btn-dark w-100">Prüfen</button>
							<div id="status" class="text-muted mt-2"></div>
						</div>
					</div>
				</form>
			
			</div>
	  	 </div>
	</div>

	<div class="row mt-3">
		<div class="col-12">
			<div id="out" class="text-muted"></div>
		</div>
	</div>
  </div>
</main>

<script>
(function(){
  const qs = s => document.querySelector(s);
  const fmtP = x => (x==null?'—':(x*100).toFixed(1)+'%');
  const fmtR = x => (x==null?'—':(x*100).toFixed(2)+'%');

  function run(){
	const symbolEl = qs('#symbol');
	const hEl = qs('#h');
	const out = qs('#out');
	const status = qs('#status');
	const btn = qs('#runBtn');

	const symbol = (symbolEl.value||'').trim().toUpperCase();
	const h = hEl.value||20;

	if(!symbol){ out.innerHTML = '<div class="alert alert-danger mb-0">Symbol fehlt.</div>'; return; }

	status.innerHTML = `
	  <div class="spinner-border spinner-border-sm text-secondary align-middle" role="status" aria-hidden="true"></div>
	  <span class="ms-1">Berechne k-NN Forecast…</span>
	`;
	btn.disabled = true;
	out.textContent = '';

	fetch(`execute/forecast/forecast.php?symbol=${encodeURIComponent(symbol)}&h=${encodeURIComponent(h)}`, {headers:{'Accept':'application/json'}})
	  .then(async r=>{
		const txt = await r.text();
		if(!r.ok){ out.innerHTML = `<div class="alert alert-danger mb-0">HTTP ${r.status} – ${txt.slice(0,300)}</div>`; return null; }
		try { return JSON.parse(txt); } catch(e){ out.innerHTML = `<div class="alert alert-danger mb-0">Kein JSON: ${txt.slice(0,300)}...</div>`; return null; }
	  })
	  .then(j=>{
		if(!j){ return; }
		if(!j.ok){ out.innerHTML = `<div class="alert alert-danger mb-0">Fehler: ${j.error||'unbekannt'}</div>`; return; }
		
		const dets = (j.detectors||[]).map(d => `${d.id} (${Math.round((d.confidence||0)*100)}%)`).join(', ') || '—';
		
		// Kopfzeile
		const name = j.name || '';
		const exch = j.exchange || '';
		const headerLine = [name, exch].filter(Boolean).join(' • ');
		const sym = j.symbol || symbol;
		const close = (j.risk && j.risk.close!=null) ? j.risk.close : null;
		const lastDate = j.last_date || null;
		
		function classifyAmpel(j){
		  const prob = j.prob_up ?? 0;
		  const conf = j.meta?.confidence ?? 0;
		  const p50  = j.retiles?.p50 ?? 0;
		  const rr50 = j.risk?.rr_p50 ?? null;      // kann null sein
		  const regime = j.meta?.regime?.trend || 'Range';
		  const stopPct = j.risk?.stop_pct ?? null; // negativ
		  const expDD   = j.expectations?.exp_maxdd ?? null; // negativ
		
		  // Hard ROT
		  if (conf < 0.35 || prob < 0.52 || (regime==='Downtrend' && p50<=0)) {
			return {label:'Rot', reason:'niedrige Edge/Confidence oder Downtrend'};
		  }
		
		  // GRÜN-Kriterien
		  const greenEdge = (prob>=0.60) && (conf>=0.50) && (p50>0) && (rr50==null || rr50>=1.2);
		  const ddOK = (stopPct==null || expDD==null) ? true : Math.abs(expDD) <= Math.abs(stopPct)*0.8;
		
		  if (greenEdge && ddOK) {
			return {label:'Grün', reason:'gute Edge & Risiko im Rahmen'};
		  }
		
		  // sonst GELB
		  return {label:'Gelb', reason:'mittlere Edge oder erhöhtes Risiko'};
		}
		
		const ampel = classifyAmpel(j);
		const badgeClass = ampel.label==='Grün' ? 'bg-success'
			: ampel.label==='Gelb' ? 'bg-warning text-dark'
			: 'bg-danger';
		
		const symHeader = `
		  <h5 class="mb-1 text-dark">
		  	${sym}
			  ${headerLine ? `— ${headerLine}` : ''}
			  <span class="badge ${badgeClass} ms-2">${ampel.label}</span>
		  </h5>
		  ${(close!=null || lastDate) ? `<div class="text-muted small">Letzter Kurs: ${close!=null?close.toFixed(2):'—'}${lastDate?` (${lastDate})`:''}</div>` : ''}
		`;
		
		// Werte aufbereiten
		const fmtP = x => (x==null?'—':(x*100).toFixed(1)+'%');
		const fmtR = x => (x==null?'—':(x*100).toFixed(2)+'%');
		
		const regimeTxt = (j.meta && j.meta.regime) ? `${j.meta.regime.trend} • vol ${j.meta.regime.vol}` : '—';
		const stopLbl   = (j.risk && j.risk.stop_mult) ? `ATR×${j.risk.stop_mult}` : 'ATR×1.5';
		const stopTxt   = (j.risk && j.risk.stop!=null) ? j.risk.stop.toFixed(2) : '—';
		const tgtTxt    = (j.targets && j.targets.t_p50) ? `${j.targets.t_p50.toFixed(2)} / ${j.targets.t_p90.toFixed(2)}` : '—';
		const rrTxt     = (j.risk && j.risk.rr_p50!=null) ? `${j.risk.rr_p50.toFixed(2)} / ${j.risk.rr_p90.toFixed(2)}` : '—';
		const confTxt   = (j.meta && j.meta.confidence!=null) ? (j.meta.confidence*100).toFixed(0)+'%' : '—';
		
		const rows = [
		  ['Ampel', `<span class="badge ${badgeClass}">${ampel.label}</span>`, ampel.reason],
		  ['Wahrscheinlichkeit ↑',   	fmtP(j.prob_up),                     	'Kalibrierte Wahrscheinlichkeit für positive Rendite über H.'],
		  ['Erwartete Rendite',      	fmtR(j.expectations?.exp_ret),       	'Gewichteter Erwartungswert der H-Tages-Rendite (k-NN).'],
		  ['Erwarteter MaxDD bis H', 	fmtR(j.expectations?.exp_maxdd),     	'Erwarteter maximaler Rückgang bis H (über Nachbarn).'],
		  ['P10',               		fmtR(j.retiles?.p10),                	'10%-Quantil der Renditeverteilung (konservativ).'],
		  ['P50 (Median)',      		fmtR(j.retiles?.p50),                	'Median der Renditeverteilung.'],
		  ['P90',               		fmtR(j.retiles?.p90),                	'90%-Quantil (optimistisch).'],
		  [`Stop (${stopLbl})`, 		stopTxt,                              	'Stop-Level basierend auf ATR-Multiplikator.'],
		  ['Ziele P50 / P90',   		tgtTxt,                              	'Abgeleitete Kursziele aus P50/P90.'],
		  ['CRV (P50 / P90)',   		rrTxt,                               	'Chance-Risiko-Verhältnis relativ zum Stop.'],
		  ['Regime',            		regimeTxt,                           	'Trend- und Volatilitätszustand.'],
		  ['Confidence',        		confTxt,                             	'Ähnlichkeitsgüte (höher = verlässlicher).'],
		  ['k-NN k',            		(j.meta&&j.meta.k)||'—',             	'Anzahl berücksichtigter Nachbarn.'],
		  ['Historie geladen',  		j.scanned||'—',                      	'Verfügbare Bars.'],
		  ['Horizont (Tage)',   		j.horizon_days||h,                   	'Prognosehorizont.']
		];
		
		const tbody = rows.map(([k,v,ex]) =>
		  `<tr>
			 <th class="w-25">${k}</th>
			 <td class="w-25">${v}</td>
			 <td class="text-muted small">${ex}</td>
		   </tr>`
		).join('');
		
		out.innerHTML = `
		  <div class="mb-4">
		  	${symHeader}
		  </div>
		  <table class="table align-middle mb-3">
			<thead class="table-dark">
				<tr>
					<th>Kennzahl</th>
					<th>Wert</th>
					<th>Erklärung</th>
				</tr>
			</thead>
			<tbody>${tbody}</tbody>
		  </table>
		  <div class="mt-2">
		  	<span class="fw-bold">Muster-Detektoren:</span> ${dets}
		  </div>
		`;

	  })
	  .catch(e=>{
		out.innerHTML = `<div class="alert alert-danger mb-0">Request-Fehler: ${String(e).slice(0,200)}</div>`;
		console.error(e);
	  })
	  .finally(()=>{ status.textContent = ''; btn.disabled = false; status.innerHTML = ''; });
  }

  document.addEventListener('click', e=>{
	if(e.target && e.target.id==='runBtn'){ run(); }
  });
  document.addEventListener('keydown', e=>{
	if(e.key==='Enter' && document.activeElement && document.activeElement.id==='symbol'){ e.preventDefault(); run(); }
  });
})();
</script>

<?php require_once __DIR__ . '/views/footer.php'; ?>