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

require_once __DIR__ . '/../../config/config.php';

$dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
]);

require_once __DIR__ . '/../../src/Auth.php';
require_once __DIR__ . '/../../src/ScopedDb.php';

if (session_status() === PHP_SESSION_NONE) {
    if (defined('SESSION_NAME')) {
        session_name(SESSION_NAME);
    }
    session_start();
}

$auth = new Auth($pdo);
$userId = $auth->requireAuth();
$db = new ScopedDb($pdo, $userId);

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

// Validate input
$accountId = trim($_GET['account_id'] ?? '');
if ($accountId === '') {
    http_response_code(400);
    echo json_encode(['error' => 'account_id required']);
    exit;
}

// Get optional date filters
$dateFrom = $_GET['date_from'] ?? null;
$dateTo = $_GET['date_to'] ?? null;
$includeTrades = isset($_GET['include_trades']) ? 
    filter_var($_GET['include_trades'], FILTER_VALIDATE_BOOLEAN) : true;
$tradeLimit = isset($_GET['trade_limit']) ? 
    min(50, max(1, intval($_GET['trade_limit']))) : 10;

// Verify account ownership - same pattern as state.php
$rows = $db->raw(
    'SELECT * FROM trading_accounts
      WHERE id = :id
        AND user_id = :uid
      LIMIT 1',
    [':id' => $accountId, ':uid' => $userId]
);

if (empty($rows)) {
    http_response_code(404);
    echo json_encode(['error' => 'account not found']);
    exit;
}

$account = $rows[0];

// Load the analytics engine
require_once __DIR__ . '/engine.php';

// Build filters array for the engine
$filters = [
    'accountId' => $accountId
];

if ($dateFrom) {
    $filters['dateFrom'] = $dateFrom;
}

if ($dateTo) {
    $filters['dateTo'] = $dateTo;
}

// Gather all analytics data
$response = [
    'success' => true,
    'data' => [
        'account' => [
            'id' => $account['id'],
            'label' => $account['label'] ?? 'Account #' . $account['id'],
            'account_type' => $account['account_type'] ?? 'unknown',
            'prop_firm_name' => $account['prop_firm_name'] ?? null,
            'status' => $account['is_active'] ? 'active' : 'inactive',
            'lifecycle_state' => $account['lifecycle_state'] ?? null,
            'created_at' => $account['created_at'],
            'updated_at' => $account['updated_at'],
            'starting_balance' => (float)$account['starting_balance'],
            'current_balance' => (float)$account['current_balance'],
            'currency' => $account['currency'] ?? 'USD',
            'initial_deposit' => (float)($account['initial_deposit'] ?? 0),
            'net_deposits' => (float)($account['net_deposits'] ?? 0),
            'net_withdrawals' => (float)($account['net_withdrawals'] ?? 0),
            'peak_equity' => (float)($account['peak_equity'] ?? 0)
        ],
        'metrics' => AnalyticsEngine::getAccountMetrics($accountId, $filters),
        'challenge' => AnalyticsEngine::getChallengeMetrics($accountId),
        'lifecycle' => AnalyticsEngine::getLifecycleJourney($accountId),
        'recent_trades' => []
    ]
];

// Get recent trades with analysis
if ($includeTrades) {
    $sql = "
        SELECT 
            id,
            instrument_display,
            direction,
            captured_at,
            closed_at,
            entry_price,
            actual_exit_price,
            actual_lots,
            broker_pnl,
            strategy_version_id
        FROM trades 
        WHERE account_id = :accountId
    ";
    $params = [':accountId' => $accountId];
    
    if ($dateFrom) {
        $sql .= " AND captured_at >= :dateFrom";
        $params[':dateFrom'] = $dateFrom;
    }
    if ($dateTo) {
        $sql .= " AND captured_at <= :dateTo";
        $params[':dateTo'] = $dateTo;
    }
    
    $sql .= " ORDER BY captured_at DESC LIMIT " . intval($tradeLimit);
    
    $recentTrades = $db->raw($sql, $params);
    
    foreach ($recentTrades as &$trade) {
        $tradeId = $trade['id'];
        
        try {
            $comparison = AnalyticsEngine::getFourStageComparison($tradeId);
            
            $trade['analysis'] = [
                'edge' => [
                    'win_rate' => $comparison['edge_snapshot']['win_rate'] ?? null,
                    'expectancy' => $comparison['edge_snapshot']['expectancy'] ?? null
                ],
                'execution' => [
                    'plan_adherence' => $comparison['scorecard']['adherence_score'] ?? null,
                    'grade' => $comparison['scorecard']['grade'] ?? null,
                    'is_rule_break' => $comparison['scorecard']['is_rule_break'] ?? false
                ],
                'deviations' => [
                    'slippage' => $comparison['manual_outcome']['slippage_entry'] ?? 0,
                    'risk_adherence' => $comparison['deviations']['plan_vs_outcome']['risk_adherence'] ?? 0
                ]
            ];
        } catch (Exception $e) {
            $trade['analysis'] = ['error' => 'Analysis unavailable'];
        }
        
        $trade['actual_lots'] = (float)($trade['actual_lots'] ?? 0);
        $trade['broker_pnl'] = (float)($trade['broker_pnl'] ?? 0);
        $trade['entry_price'] = (float)($trade['entry_price'] ?? 0);
        $trade['actual_exit_price'] = (float)($trade['actual_exit_price'] ?? 0);
    }
    
    $response['data']['recent_trades'] = $recentTrades;
}

$metrics = $response['data']['metrics'];
$response['data']['summary'] = [
    'performance_rating' => calculatePerformanceRating($metrics),
    'risk_management_grade' => calculateRiskGrade($metrics),
    'total_profitability' => $metrics['net_pnl'] > 0 ? 'profitable' : 
        ($metrics['net_pnl'] < 0 ? 'unprofitable' : 'breakeven')
];

http_response_code(200);
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

// ========================================================================
// Helper Functions
// ========================================================================

function calculatePerformanceRating($metrics) {
    $score = 0;
    $factors = 0;
    
    if ($metrics['win_rate'] >= 0.6) $score += 1;
    elseif ($metrics['win_rate'] >= 0.5) $score += 0.7;
    elseif ($metrics['win_rate'] >= 0.4) $score += 0.4;
    else $score += 0.1;
    $factors++;
    
    if ($metrics['profit_factor'] >= 2.0) $score += 1;
    elseif ($metrics['profit_factor'] >= 1.5) $score += 0.7;
    elseif ($metrics['profit_factor'] >= 1.0) $score += 0.4;
    else $score += 0.1;
    $factors++;
    
    if ($metrics['expectancy'] > 0) $score += 1;
    elseif ($metrics['expectancy'] == 0) $score += 0.4;
    else $score += 0;
    $factors++;
    
    $ddPct = abs($metrics['max_drawdown_pct']);
    if ($ddPct <= 0.05) $score += 1;
    elseif ($ddPct <= 0.10) $score += 0.7;
    elseif ($ddPct <= 0.20) $score += 0.4;
    else $score += 0.1;
    $factors++;
    
    $rating = ($score / $factors) * 5;
    
    return [
        'stars' => round($rating, 1),
        'label' => $rating >= 4.0 ? 'Excellent' :
                  ($rating >= 3.0 ? 'Good' :
                  ($rating >= 2.0 ? 'Average' : 'Needs Improvement')),
        'score' => round($rating, 1)
    ];
}

function calculateRiskGrade($metrics) {
    $score = 0;
    $factors = 0;
    
    $ddPct = abs($metrics['max_drawdown_pct']);
    if ($ddPct <= 0.05) $score += 25;
    elseif ($ddPct <= 0.10) $score += 20;
    elseif ($ddPct <= 0.15) $score += 15;
    elseif ($ddPct <= 0.25) $score += 10;
    else $score += 5;
    $factors++;
    
    if ($metrics['avg_loser'] < 0) {
        $rr = abs($metrics['avg_winner'] / $metrics['avg_loser']);
        if ($rr >= 2.0) $score += 25;
        elseif ($rr >= 1.5) $score += 20;
        elseif ($rr >= 1.0) $score += 15;
        else $score += 10;
    } else {
        $score += 15;
    }
    $factors++;
    
    if ($metrics['sortino_ratio'] >= 2.0) $score += 25;
    elseif ($metrics['sortino_ratio'] >= 1.0) $score += 20;
    elseif ($metrics['sortino_ratio'] >= 0.5) $score += 15;
    else $score += 10;
    $factors++;
    
    $percentage = ($score / ($factors * 25)) * 100;
    
    $grade = 'F';
    if ($percentage >= 95) $grade = 'A+';
    elseif ($percentage >= 90) $grade = 'A';
    elseif ($percentage >= 85) $grade = 'A-';
    elseif ($percentage >= 80) $grade = 'B+';
    elseif ($percentage >= 75) $grade = 'B';
    elseif ($percentage >= 70) $grade = 'B-';
    elseif ($percentage >= 65) $grade = 'C+';
    elseif ($percentage >= 60) $grade = 'C';
    elseif ($percentage >= 55) $grade = 'C-';
    elseif ($percentage >= 50) $grade = 'D';
    elseif ($percentage >= 40) $grade = 'E';
    
    return [
        'grade' => $grade,
        'score' => round($percentage, 1)
    ];
}