<?php
require_once dirname(__DIR__) . '/config.php';
require_once 'session_manager.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['assetKey'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Asset key is required']);
    exit;
}

$assetKey = $input['assetKey'];
$datasetName = $input['dataset'] ?? null;

try {
    // Detect user session and get user-specific data path
    detectAndStartUserSession();
    $userDataPath = getCurrentUserDataPath();
    
    if (!$userDataPath) {
        echo json_encode(['success' => false, 'message' => 'User session not found']);
        exit;
    }
    
    // Convert asset key to folder name format
    $folderName = strtolower($assetKey) . 'otc';
    $assetPath = rtrim($userDataPath, '/') . '/' . $folderName;
    
    if (!is_dir($assetPath)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Asset folder not found',
            'assetKey' => $assetKey,
            'folderName' => $folderName
        ]);
        exit;
    }
    
    // Get available datasets
    $datasets = glob($assetPath . '/dataset_*');
    
    if (empty($datasets)) {
        echo json_encode([
            'success' => false, 
            'message' => 'No datasets found for asset',
            'assetKey' => $assetKey
        ]);
        exit;
    }
    
    // Sort datasets by name (newest first)
    usort($datasets, function($a, $b) {
        return strcmp(basename($b), basename($a));
    });
    
    // Use specified dataset or latest one
    $targetDataset = $datasetName ? $assetPath . '/' . $datasetName : $datasets[0];
    
    if (!is_dir($targetDataset)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Dataset not found',
            'dataset' => $datasetName
        ]);
        exit;
    }
    
    // Load candle data
    $candleFile = $targetDataset . '/candle_data.json';
    $sentimentFile = $targetDataset . '/sentiment_data.json';
    
    if (!file_exists($candleFile) || !file_exists($sentimentFile)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Required data files not found',
            'candleFile' => file_exists($candleFile),
            'sentimentFile' => file_exists($sentimentFile)
        ]);
        exit;
    }
    
    // Read and validate data files
    $candleData = file_get_contents($candleFile);
    $sentimentData = file_get_contents($sentimentFile);
    
    if (empty($candleData) || empty($sentimentData)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Data files are empty'
        ]);
        exit;
    }
    
    $candleJson = json_decode($candleData, true);
    $sentimentJson = json_decode($sentimentData, true);
    
    if (!is_array($candleJson) || !is_array($sentimentJson)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Invalid JSON data in files'
        ]);
        exit;
    }
    
    if (empty($candleJson) || empty($sentimentJson)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Data arrays are empty'
        ]);
        exit;
    }
    
    echo json_encode([
        'success' => true,
        'assetKey' => $assetKey,
        'dataset' => basename($targetDataset),
        'candleData' => $candleJson,
        'sentimentData' => $sentimentJson,
        'candleCount' => count($candleJson),
        'sentimentCount' => count($sentimentJson),
        'username' => $_SESSION['username'] ?? 'unknown'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error loading dataset: ' . $e->getMessage()
    ]);
}
?>