<?php

namespace Mtc\Plugins\Agent\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Log;
use Mtc\Plugins\Agent\Models\TokenUsage;

class TokenUsageController extends Controller
{
    // update input and output tokens
    public function updateTokens($inputTokens, $outputTokens, $date) : void
    {
        try {
            $day = date('l', strtotime($date));
            $weekNumber = date('W', strtotime($date)); // Calculate week number
            $tokenUsage = TokenUsage::query()
                                    ->where('date', $date)
                                    ->first();

            if ($tokenUsage) {
                $tokenUsage->input_tokens += $inputTokens;
                $tokenUsage->output_tokens += $outputTokens;
                $tokenUsage->week_number = $weekNumber; // Update week number
                $tokenUsage->save();
                Log::info('Token Usage Updated for date: ' . $date);
            } else {
                TokenUsage::query()
                          ->create([
                              'date' => $date,
                              'day' => $day,
                              'week_number' => $weekNumber, // Store week number
                              'input_tokens' => $inputTokens,
                              'output_tokens' => $outputTokens,
                          ]);
                Log::info('Token Usage Created for date: ' . $date);
            }
        }
        catch (\Exception $e) {
            Log::error('Token Usage Update Error: ' . $e->getMessage());
        }

    }

    public function getTokenCount(Request $request) : JsonResponse
    {
        try {
            $date = $request->input('date');

            $weekNumber = date('W', strtotime($date));

            $tokenUsage = TokenUsage::query()->where('week_number', $weekNumber)->get();

            $totalInputTokens = $tokenUsage->sum('input_tokens');
            $totalOutputTokens = $tokenUsage->sum('output_tokens');

            return response()->json([
                'input_tokens' => $totalInputTokens,
                'output_tokens' => $totalOutputTokens,
                'total_tokens' => $totalInputTokens + $totalOutputTokens,
                'token_usage' => $tokenUsage,
                'week_number' => $weekNumber,
            ]);
        }
        catch (\Exception $e) {

            Log::error('Get Token Usage Error: ' . $e->getMessage());
            return response()->json(['error' => 'Unable to fetch token usage'], 500);
        }


    }
}
