<?php
declare(strict_types=1);

/* ==========================================================
   FX-HUNTER — AI SNAPSHOT + CONFIDENCE ENGINE (FINAL)
   ATOMIC • RACE-SAFE • PRODUCTION
   ========================================================== */

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once "/var/www/html/config.database.php";
require_once __DIR__ . "/config_webhook.php";

header("Content-Type: text/plain");

// --------------------------------------------------
// POST ONLY
// --------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit("INVALID_METHOD");
}

// --------------------------------------------------
// READ INPUT (MT5 SAFE)
// --------------------------------------------------
$raw = file_get_contents("php://input");
$data = [];
parse_str($raw, $data);
if (empty($data) && !empty($_POST)) {
    $data = $_POST;
}

// --------------------------------------------------
// REQUIRED FIELDS (STRICT CONTRACT)
// --------------------------------------------------
$required = [
    'license_key','mt5_account','symbol',
    'strategy_id','timeframe',
    'direction','regime','session',
    'ai_score','confidence',
    'after_loss','aggressive','partial_ok',
    'profit','profit_pct','r_multiple',
    'event_type'
];

foreach ($required as $f) {
    if (!isset($data[$f])) {
        http_response_code(400);
        exit("MISSING_$f");
    }
}

// --------------------------------------------------
// NORMALIZE
// --------------------------------------------------
$license_key = (string)$data['license_key'];
$mt5_account = (int)$data['mt5_account'];
$symbol      = strtoupper((string)$data['symbol']);
$strategy_id = (string)$data['strategy_id'];
$timeframe   = (int)$data['timeframe'];

$direction   = (int)$data['direction'];
$regime      = (int)$data['regime'];
$session     = (int)$data['session'];

$ai_score    = (float)$data['ai_score'];
$confidence0 = (float)$data['confidence'];

$after_loss  = (int)$data['after_loss'];
$aggressive  = (int)$data['aggressive'];
$partial_ok  = (int)$data['partial_ok'];

$profit      = (float)$data['profit'];
$profit_pct  = (float)$data['profit_pct'];
$r_multiple  = (float)$data['r_multiple'];

$event_type  = (string)$data['event_type'];

if (
    $license_key === '' ||
    $symbol === '' ||
    $strategy_id === '' ||
    $timeframe <= 0
) {
    http_response_code(400);
    exit("INVALID_INPUT");
}

// ==================================================
// 1️⃣ STORE SNAPSHOT (HISTORICAL — ALWAYS INSERT)
// ==================================================
$stmt = $db->prepare("
INSERT INTO fxh_ai_snapshots
(
    license_key, mt5_account, symbol,
    direction, regime, session,
    ai_score, confidence,
    after_loss, aggressive, partial_ok,
    profit, profit_pct, r_multiple,
    event_type, created_at
)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())
");

$stmt->bind_param(
    "sisiiiddiiiddds",
    $license_key,
    $mt5_account,
    $symbol,
    $direction,
    $regime,
    $session,
    $ai_score,
    $confidence0,
    $after_loss,
    $aggressive,
    $partial_ok,
    $profit,
    $profit_pct,
    $r_multiple,
    $event_type
);

$stmt->execute();

// ==================================================
// 2️⃣ CONFIDENCE ENGINE — ATOMIC UPSERT
// ==================================================
$isWin = ($profit > 0);
$win_inc = $isWin ? 1 : 0;

// deterministic confidence delta
$conf_delta = $isWin ? 2.5 : -5.0;

// expectancy EMA
$alpha = 0.15;

$stmt = $db->prepare("
INSERT INTO fxh_ai_confidence
(
    license_key,
    symbol,
    strategy_id,
    timeframe,
    confidence,
    trades,
    wins,
    expectancy,
    updated_at
)
VALUES
(
    ?, ?, ?, ?,
    LEAST(95, GREATEST(10, ? + ?)),
    1,
    ?,
    ?,
    NOW()
)
ON DUPLICATE KEY UPDATE
    trades     = trades + 1,
    wins       = wins + VALUES(wins),
    expectancy = (? * VALUES(expectancy)) + ((1 - ?) * expectancy),
    confidence = LEAST(95, GREATEST(10, confidence + ?)),
    updated_at = NOW()
");

$stmt->bind_param(
    "sssiddiddid",
    $license_key,
    $symbol,
    $strategy_id,
    $timeframe,
    $confidence0,
    $conf_delta,
    $win_inc,
    $profit,
    $alpha,
    $alpha,
    $conf_delta
);

$stmt->execute();

echo "OK";
