<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\TokenCalculatorService;

class TestTokenCalculation extends Command
{
    protected $signature = 'test:tokens {--word-count= : Word count config to test (e.g., 2000:3000)}';
    protected $description = 'Test and display token calculation information';

    public function handle()
    {
        $this->info('🧮 Token Calculator Test');
        $this->info('========================');
        
        $tokenCalculator = app(TokenCalculatorService::class);
        
        // Use provided word count or default from config
        $wordCountConfig = $this->option('word-count') ?: config('anthropic.content_config.article_word_count');
        $wordCount = $tokenCalculator->parseWordCount($wordCountConfig);
        
        // Display current configuration
        $this->info('📋 Current Configuration:');
        $this->line("Word Count: {$wordCount['text']} ({$wordCount['min']} - {$wordCount['max']} words)");
        $this->line('Token Multiplier: ' . config('anthropic.content_config.token_multiplier'));
        $this->line('Auto Calculate: ' . (config('anthropic.content_config.auto_calculate_tokens') ? 'Yes' : 'No'));
        $this->line('Configured Max Tokens: ' . config('anthropic.max_tokens.article'));
        
        $this->newLine();
        
        // Display token estimation
        $estimation = $tokenCalculator->getTokenEstimation($wordCount);
        $this->info('🎯 Token Estimation:');
        $this->line("Min Tokens: {$estimation['estimation']['min_tokens']}");
        $this->line("Max Tokens: {$estimation['estimation']['max_tokens']}");
        $this->line("Recommended Max (with 20% overhead): {$estimation['estimation']['with_overhead']}");
        
        $this->newLine();
        
        // Display recommendations
        $this->info('📊 Token Recommendations for Different Word Counts:');
        $recommendations = $tokenCalculator->getTokenRecommendations();
        
        foreach ($recommendations as $range => $info) {
            $isCurrent = $range === $wordCountConfig;
            $marker = $isCurrent ? ' 👈 CURRENT' : '';
            $this->line("{$range} words → {$info['tokens']} tokens ({$info['description']}){$marker}");
        }
        
        $this->newLine();
        $this->info('🔧 To change configuration, edit your .env file:');
        $this->line('CLAUDE_ARTICLE_WORD_COUNT=3000:5000');
        $this->line('CLAUDE_AUTO_CALCULATE_TOKENS=true');
        $this->line('CLAUDE_TOKEN_MULTIPLIER=3.5');
        
        $this->newLine();
        $this->info('💡 Tips:');
        $this->line('• Japanese text typically requires 2-3x more tokens than English');
        $this->line('• HTML markup adds ~15-20% overhead');
        $this->line('• Set ANTHROPIC_MAX_TOKENS_ARTICLE manually to override calculation');
        $this->line('• Use higher token limits for longer articles to avoid truncation');
    }
}