import re
import os

filepath = "/root/api-one/Telegram-Bot/index.js"
with open(filepath, "r") as f:
    content = f.read()

free_mode_block = """
// ── FREE MODE CONFIGURATION ──────────────────────────────────────────────
const fs = require('fs');
const FREEMODE_FILE = 'freemode.json';

let freeModeState = {
    active: false,
    expiresAt: null
};

if (fs.existsSync(FREEMODE_FILE)) {
    try {
        freeModeState = JSON.parse(fs.readFileSync(FREEMODE_FILE, 'utf8'));
    } catch (e) {
        console.error("Failed to parse freemode.json", e.message);
    }
}

function saveFreeModeState() {
    try {
        fs.writeFileSync(FREEMODE_FILE, JSON.stringify(freeModeState, null, 2));
    } catch (e) {
        console.error("Failed to save freemode.json", e.message);
    }
}

function isFreeModeActive() {
    if (freeModeState.active) {
        if (freeModeState.expiresAt && Date.now() > freeModeState.expiresAt) {
            freeModeState.active = false;
            freeModeState.expiresAt = null;
            saveFreeModeState();
            console.log("[FREE MODE] Expired automatically.");
            return false;
        }
        return true;
    }
    return false;
}

function parseDuration(str) {
    const match = str.match(/^(\\d+)([smhd])$/i);
    if (!match) return null;
    const value = parseInt(match[1]);
    const unit = match[2].toLowerCase();
    switch (unit) {
        case 's': return value * 1000;
        case 'm': return value * 60 * 1000;
        case 'h': return value * 60 * 60 * 1000;
        case 'd': return value * 24 * 60 * 60 * 1000;
        default: return null;
    }
}

async function triggerFreeModeBroadcast(durationText) {
    let targets = [];
    try {
        const res = await pool.query('SELECT telegram_id FROM users');
        targets = res.rows.map(r => String(r.telegram_id));
    } catch (err) {
        console.error("[FREE MODE BROADCAST ERROR]", err.message);
    }

    if (targets.length === 0) return;

    let index = 0;
    
    let durationDisplay = 'Indefinite (Manual Off)';
    if (durationText) {
        const value = parseInt(durationText);
        const unit = durationText.slice(-1);
        const unitNames = { s: 'Seconds', m: 'Minutes', h: 'Hours', d: 'Days' };
        durationDisplay = `${value} ${unitNames[unit] || ''}`;
    }

    const broadcastMsg = `🎁 <b>FREE MODE ACTIVATED / फ्री मोड चालू हो गया है</b> 🎁\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
        `Admin ne <b>Free Mode</b> activate kar diya hai! Aap bina kisi credit deduction ke unlimited searches kar sakte hain.\\n\\n` +
        `⏰ <b>Duration:</b> <code>${durationDisplay}</code>\\n\\n` +
        `⚡ Cooldown pehle ki tarah hi active rahega taaki server load normal rahe.\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
        `🤖 @MayaXAdharbot`;

    async function sendNext() {
        if (index >= targets.length) {
            console.log("[FREE MODE BROADCAST] Broadcast completed.");
            return;
        }

        const targetId = targets[index];
        index++;

        try {
            await bot.telegram.sendMessage(targetId, broadcastMsg, { parse_mode: 'HTML' });
        } catch (err) {
        }

        setTimeout(sendNext, 35);
    }

    sendNext();
}

function applyFreeMode(data) {
    if (isFreeModeActive()) {
        const hasNormalAccess = data.hasAccess;
        return {
            ...data,
            hasAccess: true,
            isFreeModeUser: !hasNormalAccess
        };
    }
    return data;
}
// ─────────────────────────────────────────────────────────────────────────

"""

if "let freeModeState" not in content:
    content = content.replace("const sessions = {};", "const sessions = {};\n" + free_mode_block)

# 2. Modify checkUserAccess caching returns
content = content.replace("return l1Cached;", "return applyFreeMode(l1Cached);")
content = content.replace("return parsed;", "return applyFreeMode(parsed);")
content = content.replace("return resultData;", "return applyFreeMode(resultData);")
content = content.replace("return { hasAccess: false, isUnlimited: false, credits: 0, planExpiresAt: null };", "return applyFreeMode({ hasAccess: false, isUnlimited: false, credits: 0, planExpiresAt: null });")


# 3. Modify admin menu 1
admin_menu1_orig = """    const adminMsg = `🛠️ <b>MAYAX ADMIN CONTROL PANEL & GUIDE</b> 🛠️\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
        `Welcome Admin! Here is the list of available features and commands to manage the Aadhaar retrieval bot:\\n\\n` +
        `⚙️ <b>Commands & Text Methods:</b>\\n` +"""

admin_menu1_new = """    const freeModeStatus = isFreeModeActive() 
        ? '🟢 ACTIVE (Unlimited Searches)' 
        : '🔴 INACTIVE (Credit System Active)';

    const adminMsg = `🛠️ <b>MAYAX ADMIN CONTROL PANEL & GUIDE</b> 🛠️\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
        `Welcome Admin! Here is the list of available features and commands to manage the Aadhaar retrieval bot:\\n\\n` +
        `🎁 <b>Free Mode Status:</b> <code>${freeModeStatus}</code>\\n` +
        `• Toggle Free Mode instantly using the button below.\\n` +
        `• Or use commands: <code>/freeon [duration]</code> (e.g., <code>/freeon 30m</code>) or <code>/freeoff</code>\\n\\n` +
        `⚙️ <b>Commands & Text Methods:</b>\\n` +"""
content = content.replace(admin_menu1_orig, admin_menu1_new)

# 4. Modify admin keyboard 1
admin_key1_orig = """        ...Markup.inlineKeyboard([
            [
                Markup.button.callback('👥 View Users List', 'ADMIN_VIEW_USERS'),"""

admin_key1_new = """        ...Markup.inlineKeyboard([
            [
                Markup.button.callback(isFreeModeActive() ? '🎁 Free Mode: ON 🟢' : '🎁 Free Mode: OFF 🔴', 'ADMIN_TOGGLE_FREEMODE')
            ],
            [
                Markup.button.callback('👥 View Users List', 'ADMIN_VIEW_USERS'),"""
content = content.replace(admin_key1_orig, admin_key1_new)


# 5. Modify admin menu 2
admin_menu2_orig = """    const adminMsg = `🛠️ <b>MAYAX ADMIN CONTROL PANEL</b> 🛠️\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
        `<b>⚡ Admin Commands Guide:</b>\\n\\n` +
        `• <b>Check User Status:</b>\\n` +"""

admin_menu2_new = """    const freeModeStatus = isFreeModeActive() 
        ? '🟢 ACTIVE (Unlimited Searches)' 
        : '🔴 INACTIVE (Credit System Active)';

    const adminMsg = `🛠️ <b>MAYAX ADMIN CONTROL PANEL</b> 🛠️\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
        `🎁 <b>Free Mode Status:</b> <code>${freeModeStatus}</code>\\n\\n` +
        `<b>⚡ Admin Commands Guide:</b>\\n\\n` +
        `• <b>Check User Status:</b>\\n` +"""
content = content.replace(admin_menu2_orig, admin_menu2_new)


# 6. Add commands and toggle action
commands_block = """
// Admin Toggle Free Mode Action Handler
bot.action('ADMIN_TOGGLE_FREEMODE', async (ctx) => {
    const userId = ctx.from.id;
    const isOwner = await isUserAdmin(userId);
    if (!isOwner) {
        return ctx.answerCbQuery("Access denied!", { show_alert: true }).catch(() => { });
    }

    if (freeModeState.active) {
        freeModeState.active = false;
        freeModeState.expiresAt = null;
        ctx.answerCbQuery("🎁 Free Mode Deactivated!").catch(() => { });

        // Broadcast deactivation notification
        let targets = [];
        try {
            const res = await pool.query('SELECT telegram_id FROM users');
            targets = res.rows.map(r => String(r.telegram_id));
        } catch (err) { }

        if (targets.length > 0) {
            const offMsg = `ℹ️ <b>FREE MODE DEACTIVATED / फ्री मोड बंद हो गया है</b> ℹ️\\n` +
                `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
                `Free Mode ab khatam ho gaya hai. Services use karne ke liye standard credit deduction ya plan system phir se lagu ho gaya hai.\\n\\n` +
                `Aap apna balance main menu me dekh sakte hain.\\n` +
                `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
                `🤖 @MayaXAdharbot`;

            let index = 0;
            function sendNextOff() {
                if (index >= targets.length) return;
                const targetId = targets[index];
                index++;
                bot.telegram.sendMessage(targetId, offMsg, { parse_mode: 'HTML' }).catch(()=>{});
                setTimeout(sendNextOff, 35);
            }
            sendNextOff();
        }
    } else {
        freeModeState.active = true;
        freeModeState.expiresAt = null;
        ctx.answerCbQuery("🎁 Free Mode Activated (Indefinite)!").catch(() => { });
        await triggerFreeModeBroadcast(null);
    }
    saveFreeModeState();

    const freeModeStatus = isFreeModeActive() 
        ? '🟢 ACTIVE (Unlimited Searches)' 
        : '🔴 INACTIVE (Credit System Active)';

    const adminMsg = `🛠️ <b>MAYAX ADMIN CONTROL PANEL</b> 🛠️\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
        `🎁 <b>Free Mode Status:</b> <code>${freeModeStatus}</code>\\n\\n` +
        `<b>⚡ Admin Commands Guide:</b>\\n\\n` +
        `• <b>Check User Status:</b>\\n` +
        `  <code>/userstatus [telegram_id]</code>\\n` +
        `  <i>(Displays credits, active plan, thread id, and total searches)</i>\\n\\n` +
        `• <b>Export Data (Clean/Light):</b>\\n` +
        `  <code>/dbexport</code>\\n\\n` +
        `• <b>Full Database Backup (Compressed GZ):</b>\\n` +
        `  <code>/dbbackup</code>\\n\\n` +
        `• <b>Add / Remove User Credits:</b>\\n` +
        `  <code>/addcredit [telegram_id] [amount]</code>\\n` +
        `  <code>/rmcredit [telegram_id] [amount]</code>\\n\\n` +
        `• <b>Manage User Plans:</b>\\n` +
        `  <code>/addplan [telegram_id] [daily|weekly|monthly|yearly]</code>\\n\\n` +
        `• <b>Add / Remove Retailer:</b>\\n` +
        `  <code>/addretailer [telegram_id]</code>\\n` +
        `  <code>/removeretailer [telegram_id]</code>\\n\\n` +
        `• <b>Broadcast Message:</b>\\n` +
        `  Reply to any message with <code>/broadcast [flags]</code>\\n` +
        `━━━━━━━━━━━━━━━━━━━━━━━━━━`;

    ctx.editMessageText(adminMsg, {
        parse_mode: 'HTML',
        ...Markup.inlineKeyboard([
            [
                Markup.button.callback(isFreeModeActive() ? '🎁 Free Mode: ON 🟢' : '🎁 Free Mode: OFF 🔴', 'ADMIN_TOGGLE_FREEMODE')
            ],
            [
                Markup.button.callback('👥 View Users List', 'ADMIN_VIEW_USERS'),
                Markup.button.callback('➕ Add User Credits', 'ADMIN_ADD_CREDITS_PROMPT')
            ],
            [
                Markup.button.callback('🔙 Back to Main Menu', 'ADMIN_BACK_TO_MAIN')
            ]
        ])
    });
});

bot.command('freeon', async (ctx) => {
    const userId = ctx.from.id;
    const isOwner = await isUserAdmin(userId);
    if (!isOwner) {
        return ctx.reply("❌ You are not authorized to run this command.");
    }

    const args = ctx.message.text.split(' ').slice(1);
    let durationMs = null;
    let durationText = '';

    if (args.length > 0) {
        durationText = args[0];
        durationMs = parseDuration(durationText);
        if (!durationMs) {
            return ctx.reply("❌ Invalid duration format! Use e.g. <code>30s</code>, <code>10m</code>, <code>2h</code>, or <code>1d</code>. Or use /freeon without arguments for indefinite.", { parse_mode: 'HTML' });
        }
    }

    freeModeState.active = true;
    if (durationMs) {
        freeModeState.expiresAt = Date.now() + durationMs;
    } else {
        freeModeState.expiresAt = null;
    }
    saveFreeModeState();

    let displayTime = durationMs ? `for ${durationText}` : 'indefinitely';
    await ctx.reply(`✅ <b>Free Mode ENABLED</b> ${displayTime}!\\n\\nAll non-subscribing users now have unlimited searches. Broadcast notification has started.`, { parse_mode: 'HTML' });

    await triggerFreeModeBroadcast(durationText || null);
});

bot.command('freeoff', async (ctx) => {
    const userId = ctx.from.id;
    const isOwner = await isUserAdmin(userId);
    if (!isOwner) {
        return ctx.reply("❌ You are not authorized to run this command.");
    }

    freeModeState.active = false;
    freeModeState.expiresAt = null;
    saveFreeModeState();

    await ctx.reply("❌ <b>Free Mode DISABLED!</b>\\n\\nCredit rules are now active again.", { parse_mode: 'HTML' });

    let targets = [];
    try {
        const res = await pool.query('SELECT telegram_id FROM users');
        targets = res.rows.map(r => String(r.telegram_id));
    } catch (err) { }

    if (targets.length > 0) {
        const offMsg = `ℹ️ <b>FREE MODE DEACTIVATED / फ्री मोड बंद हो गया है</b> ℹ️\\n` +
            `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
            `Free Mode ab khatam ho gaya hai. Services use karne ke liye standard credit deduction ya plan system phir se lagu ho gaya hai.\\n\\n` +
            `Aap apna balance main menu me dekh sakte hain.\\n` +
            `━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +
            `🤖 @MayaXAdharbot`;

        let index = 0;
        function sendNextOff() {
            if (index >= targets.length) return;
            const targetId = targets[index];
            index++;
            bot.telegram.sendMessage(targetId, offMsg, { parse_mode: 'HTML' }).catch(()=>{});
            setTimeout(sendNextOff, 35);
        }
        sendNextOff();
    }
});
"""

if "ADMIN_TOGGLE_FREEMODE" not in content:
    content = content.replace("bot.action('ADMIN_VIEW_USERS'", commands_block + "\nbot.action('ADMIN_VIEW_USERS'")

with open(filepath, "w") as f:
    f.write(content)

print("Patch applied successfully.")
