<?php

namespace App\Services;

class TokenCalculatorService
{
    /**
     * Parse word count configuration (can be range or single number)
     */
    public function parseWordCount(string $config): array
    {
        if (strpos($config, ':') !== false) {
            [$min, $max] = explode(':', $config);
            return [
                'min' => (int) $min,
                'max' => (int) $max,
                'text' => "{$min}〜{$max}語"
            ];
        }
        
        $count = (int) $config;
        return [
            'min' => $count,
            'max' => $count,
            'text' => "{$count}語"
        ];
    }
    
    /**
     * Calculate recommended max tokens based on word count
     */
    public function calculateMaxTokens(array $wordCount): int
    {
        $autoCalculate = config('anthropic.content_config.auto_calculate_tokens', true);
        $configuredMaxTokens = config('anthropic.max_tokens.article', 8000);
        
        if (!$autoCalculate) {
            return $configuredMaxTokens;
        }
        
        $tokenMultiplier = config('anthropic.content_config.token_multiplier', 3.5);
        $maxWords = $wordCount['max'];
        
        // Calculate tokens with overhead for HTML markup and formatting
        $calculatedTokens = (int) ceil($maxWords * $tokenMultiplier * 1.2); // 20% overhead
        
        // Ensure we don't go below the configured minimum
        $recommendedTokens = max($calculatedTokens, $configuredMaxTokens);
        
        return $recommendedTokens;
    }
    
    /**
     * Get token estimation info for display
     */
    public function getTokenEstimation(array $wordCount): array
    {
        $maxTokens = $this->calculateMaxTokens($wordCount);
        $tokenMultiplier = config('anthropic.content_config.token_multiplier', 3.5);
        
        return [
            'word_count' => $wordCount,
            'max_tokens' => $maxTokens,
            'token_multiplier' => $tokenMultiplier,
            'estimation' => [
                'min_tokens' => (int) ceil($wordCount['min'] * $tokenMultiplier),
                'max_tokens' => (int) ceil($wordCount['max'] * $tokenMultiplier),
                'with_overhead' => $maxTokens
            ]
        ];
    }
    
    /**
     * Get recommended token limits based on word count ranges
     */
    public function getTokenRecommendations(): array
    {
        return [
            '1000:2000' => ['tokens' => 6000, 'description' => 'Short articles'],
            '2000:3000' => ['tokens' => 10000, 'description' => 'Medium articles (current default)'],
            '3000:5000' => ['tokens' => 16000, 'description' => 'Long articles'],
            '5000:7000' => ['tokens' => 22000, 'description' => 'Very long articles'],
            '7000:10000' => ['tokens' => 32000, 'description' => 'Extended articles (enterprise)']
        ];
    }
}