<?php
// /traderalign/api/calculator/instrument-hint.php
//
// GET /api/calculator/instrument-hint?instrument=us30
//
// Narrow, single-instrument endpoint — part of the 2026-08-11 calculator
// exposure-closure pass (see CLAUDE.md's dated session entry and
// docs/architecture/CALCULATOR_BUSINESS_LOGIC_PHP_MIGRATION.md). Exists
// because one UI feature — the index/commodity/stock "Tick Value ($/pt/lot)"
// hint in calculator-source.html's toggleInstrument() — genuinely needs a
// real, MT5-tuned constant BEFORE the trader clicks Calculate, so it can't
// be satisfied by the POST /api/calculator/compute response the way every
// other post-click UI read now is. Rather than shipping the full 56-
// instrument precision table to every page load (calculator-source.html's
// client-side INSTRUMENTS object no longer carries these fields at all —
// see that file's own comment), this endpoint hands back only the two
// fields the hint actually renders, for exactly one instrument at a time,
// authenticated. Reconstructing the full table this way would require 56
// separate authenticated requests instead of one page-source dump — raises
// the bar substantially without claiming to be a perfect defense (still
// technically enumerable one instrument at a time), matching the tradeoff
// Kevin explicitly signed off on for this pass.
//
// Response (200):
//   { "success": true, "instrument": "us30",
//     "tick_value": 5.00, "tick_note": "..." }
//   tick_value/tick_note are both null for an instrument with no index-
//   spec tick data (i.e. every instrument outside the ~16-key "isIndex"
//   list calculator-source.html's toggleInstrument() already gates this
//   feature behind) — a real, honest "nothing to show", not an error.
//
// Errors:
//   400 { "success": false, "error": "..." }  — missing/unknown instrument
//   401 (via $auth->requireAuth())
//   405 { "success": false, "error": "Method not allowed" }

require_once __DIR__ . '/../../src/CalculatorEngine.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$userId = $auth->requireAuth();

$instrument = strtolower(trim((string)($_GET['instrument'] ?? '')));
if ($instrument === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing instrument']);
    exit;
}

$inst = CalculatorEngine::INSTRUMENTS[$instrument] ?? null;
if ($inst === null) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => "Unknown instrument: {$instrument}"]);
    exit;
}

echo json_encode([
    'success' => true,
    'instrument' => $instrument,
    'tick_value' => $inst['tickValue'] ?? null,
    'tick_note' => $inst['tickNote'] ?? null,
]);
