// services/style-detector.service.ts
import {Injectable, Logger} from '@nestjs/common';
import {ContentStyle} from '../enum/style.enum';
import {ContentTone} from '../enum/tone.enum';
import {Language} from "../../../common/interfaces/language.prompt.interface";
import {getLanguageByJSTTime} from "../../../shared/helper";

/**
 * Heuristic keyword-based detector - 0 token cost.
 * Chỉ fallback gọi AI nếu không match gì (optional).
 */
@Injectable()
export class StyleDetectorService {
    private readonly logger = new Logger(StyleDetectorService.name);
    private readonly styleKeywords: Record<ContentStyle, RegExp> = {
        [ContentStyle.CRYPTO]: /\b(btc|eth|sol|crypto|token|defi|nft|airdrop|bullish|bearish|pump|dump|web3|dex|memecoin|on-chain|layer2|testnet|mainnet|whitelist|degen|\$[a-z]{2,10})\b/i,
        [ContentStyle.BREAKING_NEWS]: /\b(breaking|Tin nhanh|họp báo|cảnh báo|🔴|just in|urgent|announced|report(ed)?|confirms?|leaked)\b/i,
        [ContentStyle.TECH]: /\b(ai model|ai tool|ai agent|docker|kubernetes|microservice|claude|cursor|open ai|api|sdk|framework|nestjs|react|python|github|opensource|llm|gpt|model)\b/i,
        [ContentStyle.FINANCE]: /\b(stock|dự báo|market|fed|inflation|nasdaq|sp500|s&p500|earnings|ipo|yield|portfolio|hedge|cpi|gdp|quarterly|interest rate|lãi suất|chứng khoán|cổ phiếu|quỹ|bond)\b/i,
        [ContentStyle.LIFESTYLE]: /\b(morning|coffee|travel|family|food|recipe|wellness|selfcare|self-care|mindset|routine,grateful|vibe|sunday|weekend|balance)\b/i,
        [ContentStyle.MEME]: /\b(lol|lmao|meme|funny|hits different|living rent free|understood the assignment|no cap|fr fr|😂|🤣)\b/i,
        [ContentStyle.EDUCATIONAL]: /\b(how to|tutorial|guide|learn|explain|tips?)\b/i,
        [ContentStyle.OPINION]: /\b(opinion|hot take|unpopular|i think|my take|controversial|change my mind|fight me|disagree)\b/i,
        [ContentStyle.STORYTELLING]: /\b(thread|story time|true story|happened to me|years ago|flashback|let me tell you|here's how)\b/i,
        [ContentStyle.THREAD]: /\b(thread| 🧵|a thread|part 1)\b/i,
        [ContentStyle.GENERAL]: /.^/, // never match
    };

    private readonly toneKeywords: Record<ContentTone, RegExp> = {
        [ContentTone.URGENT]: /\b(urgent|now|🔴|immediately|just dropped|breaking|họp báo|cảnh báo|khẩn|quan trọng|  thông báo gấp|alert)\b/i,
        [ContentTone.HYPE]: /\b(lfg|huge|massive|insane|alpha|don't miss|🚀|🔥)\b/i,
        [ContentTone.HUMOROUS]: /\b(lol|funny|joke|meme|plot twist|not me|understood the assignment|lmao|bruh|no way|bestie)\b/i,
        [ContentTone.PROFESSIONAL]: /\b(report|analysis|official|statement)\b/i,
        [ContentTone.INFORMATIVE]: /\b(study|data|research|found|shows)\b/i,
        [ContentTone.EMPATHETIC]: /\b(feel|feeling|understand|hard|tough|going through|been there|sending love|mental health|burnout|struggle)\b/i,
        [ContentTone.PROVOCATIVE]: /\b(change my mind|unpopular opinion|fight me|controversial|hot take|nobody talks about|am i wrong, be honest)\b/i,
        [ContentTone.AUTHORITATIVE]: /\b(the truth is|let me be clear|fact:|experience shows|from my experience|data shows|evidence|proven|decades)\b/i,
        [ContentTone.CASUAL]: /.^/,
    };

    detectStyle(text: string): ContentStyle {
        this.logger.debug('===> styleDetectorService_detectStyle', text);
        const scores: Partial<Record<ContentStyle, number>> = {};
        for (const [style, regex] of Object.entries(this.styleKeywords)) {
            const matches = text.match(new RegExp(regex, 'gi'));
            if (matches) scores[style as ContentStyle] = matches.length;
        }
        const best = Object.entries(scores).sort((a, b) => b[1]! - a[1]!)[0];
        return (best?.[0] as ContentStyle) ?? ContentStyle.GENERAL;
    }

    detectTone(text: string): ContentTone {
        this.logger.debug('===> styleDetectorService_detectTone', text);

        for (const [tone, regex] of Object.entries(this.toneKeywords)) {
            if (regex.test(text)) return tone as ContentTone;
        }
        return ContentTone.CASUAL;
    }

    detectLanguageFromTelegramAutoContent(text: string): Language {
        if (/nhật[ _]bản/i.test(text)) return "ja";
        if (/#hàn_quốc/i.test(text)) return "ko";

        // return getLanguageByJSTTime();
        //
        return "en"
    }
}