<?php

namespace Mtc\Plugins\Agent\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
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();

            $inputTokens = (int) $inputTokens;
            $outputTokens = (int) $outputTokens;

            if ($tokenUsage) {
                TokenUsage::query()->where('date', $date)->update([
                    'input_tokens' => DB::raw("input_tokens + {$inputTokens}"),
                    'output_tokens' => DB::raw("output_tokens + {$outputTokens}"),
                    'week_number' => $weekNumber,
                ]);
                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);
        }


    }
}
