<?php
/**
 * Load full strategy data for pre-filling the strategy editing form
 * GET /api/strategy/load?id=STRATEGY_ID
 */

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

try {
    $userId = $auth->requireAuth();
    
    $strategyId = $_GET['id'] ?? null;
    if (!$strategyId) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing strategy ID']);
        exit;
    }
    
    // 1. Fetch strategy — verify ownership
    $strategy = $db->selectById('strategies', $strategyId);
    if (!$strategy) {
        http_response_code(404);
        echo json_encode(['error' => 'Strategy not found']);
        exit;
    }
    
    // Verify ownership
    if ($strategy['user_id'] !== $userId) {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        exit;
    }
    
    // 2. Fetch current version
    $versionId = $strategy['current_version_id'];
    $version = $db->selectById('strategy_versions', $versionId);
    if (!$version) {
        http_response_code(404);
        echo json_encode(['error' => 'Strategy version not found']);
        exit;
    }
    
    // 3. Fetch checklist items
    $checklistItems = $db->select(
        'checklist_items',
        'strategy_version_id = :vid',
        [':vid' => $versionId],
        '*',
        "FIELD(category, 'setup', 'entry', 'risk', 'execution'), position"
    );
    
    // Build response
    $response = [
        'strategy' => [
            'id'                  => $strategy['id'],
            'name'                => $strategy['name'],
            'description'         => $strategy['description'] ?? '',
            'trading_style'       => $strategy['trading_style'] ?? 'day_trader',
            'is_active'           => (bool)$strategy['is_active'],
            'current_version_id'  => $strategy['current_version_id'],
        ],
        'version' => [
            'id'                    => $version['id'],
            'strategy_id'           => $version['strategy_id'],
            'version_number'        => (int)$version['version_number'],
            'backtested_win_rate'   => $version['backtested_win_rate'] !== null ? (float)$version['backtested_win_rate'] : null,
            'backtested_avg_rr'     => $version['backtested_avg_rr'] !== null ? (float)$version['backtested_avg_rr'] : null,
            'max_risk_per_trade_pct'=> $version['max_risk_per_trade_pct'] !== null ? (float)$version['max_risk_per_trade_pct'] : null,
            'max_losing_streak'     => $version['max_losing_streak'] !== null ? (int)$version['max_losing_streak'] : null,
            'max_trades_per_day'    => $version['max_trades_per_day'] !== null ? (int)$version['max_trades_per_day'] : null,
            'max_trades_per_week'   => $version['max_trades_per_week'] !== null ? (int)$version['max_trades_per_week'] : null,
            'instruments_traded'    => json_decode($version['instruments_traded'] ?? '[]', true) ?: [],
            'timeframes_traded'     => json_decode($version['timeframes_traded'] ?? '[]', true) ?: [],
            'session_preference'    => json_decode($version['session_preference'] ?? '[]', true) ?: [],
            'setup_criteria'        => json_decode($version['setup_criteria'] ?? '[]', true) ?: [],
            'entry_triggers'        => json_decode($version['entry_triggers'] ?? '[]', true) ?: [],
            'sl_rules'              => json_decode($version['sl_rules'] ?? '[]', true) ?: [],
            'tp_rules'              => json_decode($version['tp_rules'] ?? '[]', true) ?: [],
            'move_to_be_rule'       => $version['move_to_be_rule'] ?? '',
            'polished_by'           => $version['polished_by'] ?? 'manual',
        ],
        'checklist_items' => array_map(function($item) {
            return [
                'id'                  => $item['id'],
                'strategy_version_id' => $item['strategy_version_id'],
                'category'            => $item['category'],
                'position'            => (int)$item['position'],
                'raw_text'            => $item['raw_text'] ?? '',
                'polished_text'       => $item['polished_text'] ?? '',
                'verification_hint'   => $item['verification_hint'] ?? '',
                'is_required'         => (bool)$item['is_required'],
            ];
        }, $checklistItems ?: []),
    ];
    
    echo json_encode($response);
    
} catch (\Throwable $e) {
    error_log("Strategy load error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}