File size: 8,956 Bytes
1884bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import motor.motor_asyncio
import os
import json
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

class DatabaseManager:
    def __init__(self, uri=None):
        # Fallback for local testing if MONGO_URI is not set
        self.uri = uri or os.getenv('MONGO_URI')
        if not self.uri:
            logger.warning("⚠️ MONGO_URI is not set in environment. Falling back to local JSON mode.")
            self.client = None
            self.db = None
        else:
            self.client = motor.motor_asyncio.AsyncIOMotorClient(self.uri)
            self.db = self.client['bytebet_db']
            logger.info("✅ Connected to MongoDB Atlas.")

    # --- Migration Logic ---
    async def migrate_from_json(self):
        if not self.db:
            return

        json_files = {
            'user_balances.json': self.db.balances,
            'slaves.json': self.db.slaves,
            'delayed_transfers.json': self.db.transfers,
            'work_cooldowns.json': self.db.cooldowns,
            'user_inventory.json': self.db.inventory,
            'lottery_data.json': self.db.lottery,
            'stock_market_data.json': self.db.stocks
        }

        for filename, collection in json_files.items():
            if os.path.exists(filename):
                try:
                    with open(filename, 'r') as file:
                        data = json.load(file)
                    
                    # Check if already migrated
                    count = await collection.count_documents({})
                    if count > 0:
                        logger.info(f"⏩ {filename} already migrated.")
                        continue

                    logger.info(f"📦 Migrating {filename} to MongoDB...")
                    
                    if filename == 'user_balances.json':
                        docs = []
                        for guild_id, users in data.items():
                            for user_id, bal in users.items():
                                docs.append({'guild_id': guild_id, 'user_id': user_id, 'wallet': bal['wallet'], 'bank': bal['bank']})
                        if docs: await collection.insert_many(docs)
                    
                    elif filename == 'slaves.json':
                        docs = []
                        for guild_id, slaves in data.items():
                            for slave_id, info in slaves.items():
                                docs.append({'guild_id': guild_id, 'slave_id': slave_id, **info})
                        if docs: await collection.insert_many(docs)
                    
                    elif filename == 'delayed_transfers.json':
                        if data: await collection.insert_many(data)
                    
                    elif filename == 'work_cooldowns.json':
                        docs = []
                        for guild_id, users in data.items():
                            for user_id, ts in users.items():
                                docs.append({'guild_id': guild_id, 'user_id': user_id, 'type': 'work', 'expires_at': ts})
                        if docs: await collection.insert_many(docs)

                    elif filename == 'user_inventory.json':
                        docs = []
                        for guild_id, users in data.items():
                            for user_id, items in users.items():
                                docs.append({'guild_id': guild_id, 'user_id': user_id, 'items': items})
                        if docs: await collection.insert_many(docs)

                    elif filename == 'lottery_data.json':
                        # Lottery data is usually global or per-guild, adding guild_id as 'global'
                        data['guild_id'] = 'global'
                        await collection.insert_one(data)

                    elif filename == 'stock_market_data.json':
                        docs = []
                        for symbol, info in data.items():
                            docs.append({'symbol': symbol, **info})
                        if docs: await collection.insert_many(docs)

                    logger.info(f"✅ Migrated {filename} successfully.")
                    # Optionally rename the file to avoid re-migration
                    # os.rename(filename, f"{filename}.bak")
                except Exception as e:
                    logger.error(f"❌ Error migrating {filename}: {e}")

    # --- Balance Ops ---
    async def get_balance(self, guild_id, user_id):
        if not self.db:
            return None # Use local fallback if needed
        doc = await self.db.balances.find_one({'guild_id': str(guild_id), 'user_id': str(user_id)})
        return doc or {'guild_id': str(guild_id), 'user_id': str(user_id), 'wallet': 500, 'bank': 0}

    async def update_balance(self, guild_id, user_id, wallet, bank):
        if not self.db: return
        await self.db.balances.update_one(
            {'guild_id': str(guild_id), 'user_id': str(user_id)},
            {'$set': {'wallet': wallet, 'bank': bank}},
            upsert=True
        )

    async def get_server_balances(self, guild_id):
        if not self.db: return {}
        cursor = self.db.balances.find({'guild_id': str(guild_id)})
        balances = {}
        async for doc in cursor:
            balances[doc['user_id']] = {'wallet': doc['wallet'], 'bank': doc['bank']}
        return balances

    # --- Cooldown Ops ---
    async def get_cooldown(self, guild_id, user_id, cooldown_type):
        if not self.db: return None
        doc = await self.db.cooldowns.find_one({'guild_id': str(guild_id), 'user_id': str(user_id), 'type': cooldown_type})
        return doc['expires_at'] if doc else None

    async def set_cooldown(self, guild_id, user_id, cooldown_type, expires_at):
        if not self.db: return
        await self.db.cooldowns.update_one(
            {'guild_id': str(guild_id), 'user_id': str(user_id), 'type': cooldown_type},
            {'$set': {'expires_at': expires_at}},
            upsert=True
        )

    # --- Slavery Ops ---
    async def get_slave_data(self, guild_id):
        if not self.db: return {}
        cursor = self.db.slaves.find({'guild_id': str(guild_id)})
        slaves = {}
        async for doc in cursor:
            sid = doc['slave_id']
            data = doc.copy()
            del data['_id'], data['slave_id'], data['guild_id']
            slaves[sid] = data
        return slaves

    async def update_slave(self, guild_id, slave_id, data):
        if not self.db: return
        await self.db.slaves.update_one(
            {'guild_id': str(guild_id), 'slave_id': str(slave_id)},
            {'$set': data},
            upsert=True
        )

    async def remove_slave(self, guild_id, slave_id):
        if not self.db: return
        await self.db.slaves.delete_one({'guild_id': str(guild_id), 'slave_id': str(slave_id)})

    # --- Stock Ops ---
    async def get_stocks(self):
        if not self.db: return {}
        cursor = self.db.stocks.find({})
        stocks = {}
        async for doc in cursor:
            symbol = doc['symbol']
            data = doc.copy()
            del data['_id'], data['symbol']
            stocks[symbol] = data
        return stocks

    async def update_stock(self, symbol, data):
        if not self.db: return
        await self.db.stocks.update_one(
            {'symbol': symbol},
            {'$set': data},
            upsert=True
        )

    # --- Lottery Ops ---
    async def get_lottery(self):
        if not self.db: return None
        return await self.db.lottery.find_one({'guild_id': 'global'})

    async def update_lottery(self, data):
        if not self.db: return
        await self.db.lottery.update_one(
            {'guild_id': 'global'},
            {'$set': data},
            upsert=True
        )

    # --- Inventory Ops ---
    async def get_inventory(self, guild_id, user_id):
        if not self.db: return {}
        doc = await self.db.inventory.find_one({'guild_id': str(guild_id), 'user_id': str(user_id)})
        return doc['items'] if doc else {}

    async def update_inventory(self, guild_id, user_id, items):
        if not self.db: return
        await self.db.inventory.update_one(
            {'guild_id': str(guild_id), 'user_id': str(user_id)},
            {'$set': {'items': items}},
            upsert=True
        )

    # --- Portfolio Ops ---
    async def get_portfolio(self, guild_id, user_id):
        if not self.db: return {}
        doc = await self.db.portfolios.find_one({'guild_id': str(guild_id), 'user_id': str(user_id)})
        return doc['stocks'] if doc else {}

    async def update_portfolio(self, guild_id, user_id, stocks):
        if not self.db: return
        await self.db.portfolios.update_one(
            {'guild_id': str(guild_id), 'user_id': str(user_id)},
            {'$set': {'stocks': stocks}},
            upsert=True
        )