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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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
ThutoAI - Complete Student Assistant with School Management
Enhanced version for Hugging Face deployment
"""
import os
from flask import Flask, request, jsonify, render_template
from dotenv import load_dotenv
from school_service import school_service
from admin_service import admin_service
import json

# Load environment variables
load_dotenv()

app = Flask(__name__)

# Get the API key from environment variables
api_key = os.getenv("OPENAI_API_KEY")

if not api_key:
    print("WARNING: OPENAI_API_KEY is not set. Chat functionality will not work.")
    client = None
else:
    try:
        from openai import OpenAI
        client = OpenAI()  # Will use OPENAI_API_KEY from environment
        print("OpenAI client initialized successfully")
    except Exception as e:
        print(f"Error initializing OpenAI client: {e}")
        client = None

@app.route("/")
def home():
    """Serve the enhanced chat web interface"""
    return render_template('index.html')

@app.route("/dashboard")
def dashboard():
    """Serve the student dashboard"""
    try:
        student_summary = school_service.get_student_summary()
        return jsonify({
            "success": True,
            "data": student_summary
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route("/announcements")
def get_announcements():
    """Get recent announcements"""
    try:
        announcements = school_service.get_recent_announcements()
        return jsonify({
            "success": True,
            "announcements": announcements
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route("/exams")
def get_exams():
    """Get upcoming exams"""
    try:
        exams = school_service.get_upcoming_exams()
        return jsonify({
            "success": True,
            "exams": exams
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route("/tests")
def get_tests():
    """Get upcoming tests and assignments"""
    try:
        tests = school_service.get_upcoming_tests_assignments()
        return jsonify({
            "success": True,
            "tests": tests
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route("/grades")
def get_grades():
    """Get student grades"""
    try:
        student_id = request.args.get('student_id', 'STU001')
        subject = request.args.get('subject', None)
        grades = school_service.get_student_grades(student_id, subject)
        return jsonify({
            "success": True,
            "grades": grades
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route("/events")
def get_events():
    """Get upcoming school events"""
    try:
        events = school_service.get_upcoming_events()
        return jsonify({
            "success": True,
            "events": events
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route("/search")
def search_school_info():
    """Search school information"""
    try:
        query = request.args.get('q', '')
        if not query:
            return jsonify({
                "success": False,
                "error": "Search query is required"
            }), 400
        
        results = school_service.search_school_info(query)
        return jsonify({
            "success": True,
            "results": results,
            "query": query
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route("/chat", methods=["POST"])
def chat():
    """Enhanced chat with school context"""
    try:
        if not client:
            return jsonify({"error": "OpenAI API key not configured"}), 500
            
        data = request.json
        user_message = data.get("message", "")

        if not user_message:
            return jsonify({"error": "Message is required"}), 400

        # Get school context for AI
        school_context = school_service.format_school_context_for_ai()
        
        # Enhanced system prompt for student assistant
        system_prompt = f"""You are ThutoAI, an AI assistant specifically designed to help students with their academic life. You have access to real-time school information and should use it to provide contextual, helpful responses.

{school_context}

Your role is to:
1. Help students with academic questions and study support
2. Provide information about school announcements, exams, tests, and events
3. Offer study tips, time management advice, and motivation
4. Help with stress management and emotional support
5. Answer questions about grades and academic performance
6. Remind students about important dates and deadlines

Always be encouraging, supportive, and student-friendly. Use the school information context to provide specific, relevant answers. If asked about school-specific information, refer to the context provided above."""

        # Use the enhanced OpenAI client
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_message}
            ],
            temperature=0.7,
            max_tokens=1000
        )

        reply = response.choices[0].message.content
        
        # Check if the query might be school-specific and add relevant info
        school_keywords = ['exam', 'test', 'grade', 'announcement', 'assignment', 'due', 'schedule']
        if any(keyword in user_message.lower() for keyword in school_keywords):
            search_results = school_service.search_school_info(user_message)
            if search_results:
                reply += "\n\n📚 **Related School Information:**\n"
                for result in search_results[:3]:  # Show top 3 results
                    if result['type'] == 'exam':
                        reply += f"• **{result['name']}** ({result['subject']}) - {result['date']} at {result['time']}\n"
                    elif result['type'] == 'announcement':
                        reply += f"• **{result['title']}** - {result['content'][:100]}...\n"
                    elif result['type'] == 'test_assignment':
                        reply += f"• **{result['title']}** ({result['subject']}) - Due: {result['due_date']}\n"

        return jsonify({"reply": reply})

    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ==================== ADMIN ROUTES ====================

@app.route("/admin/login")
def admin_login_page():
    """Serve admin login page"""
    return render_template('admin_login.html')

@app.route("/admin/login", methods=["POST"])
def admin_login():
    """Handle admin login"""
    try:
        data = request.json
        username = data.get("username")
        password = data.get("password")
        
        if not username or not password:
            return jsonify({"success": False, "error": "Username and password required"}), 400
        
        admin = admin_service.authenticate_admin(username, password)
        
        if admin:
            return jsonify({"success": True, "admin": admin})
        else:
            return jsonify({"success": False, "error": "Invalid credentials"}), 401
            
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/admin/dashboard")
def admin_dashboard():
    """Serve admin dashboard"""
    return render_template('admin_dashboard.html')

@app.route("/admin/stats")
def admin_stats():
    """Get admin dashboard statistics"""
    try:
        stats = admin_service.get_admin_dashboard_stats()
        return jsonify({"success": True, "stats": stats})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

# Announcement management routes
@app.route("/admin/announcements", methods=["GET"])
def admin_get_announcements():
    """Get all announcements for admin"""
    try:
        announcements = admin_service.get_all_announcements()
        return jsonify({"success": True, "announcements": announcements})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/admin/announcements", methods=["POST"])
def admin_create_announcement():
    """Create new announcement"""
    try:
        data = request.json
        announcement_id = admin_service.create_announcement(
            title=data.get("title"),
            content=data.get("content"),
            priority=data.get("priority", "normal"),
            target_audience=data.get("target_audience", "all"),
            expires_at=data.get("expires_at")
        )
        return jsonify({"success": True, "id": announcement_id})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/admin/announcements/<int:announcement_id>", methods=["DELETE"])
def admin_delete_announcement(announcement_id):
    """Delete announcement"""
    try:
        admin_service.delete_announcement(announcement_id)
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

# Syllabus management routes
@app.route("/admin/syllabus", methods=["GET"])
def admin_get_syllabus():
    """Get all syllabus entries"""
    try:
        syllabus = admin_service.get_syllabus()
        return jsonify({"success": True, "syllabus": syllabus})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/admin/syllabus", methods=["POST"])
def admin_create_syllabus():
    """Create new syllabus entry"""
    try:
        data = request.json
        syllabus_id = admin_service.create_syllabus(
            subject=data.get("subject"),
            grade_level=data.get("grade_level"),
            chapter_number=data.get("chapter_number"),
            chapter_title=data.get("chapter_title"),
            topics=data.get("topics"),
            learning_objectives=data.get("learning_objectives"),
            duration_weeks=data.get("duration_weeks"),
            resources=data.get("resources"),
            assessment_methods=data.get("assessment_methods")
        )
        return jsonify({"success": True, "id": syllabus_id})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/admin/syllabus/<int:syllabus_id>", methods=["DELETE"])
def admin_delete_syllabus(syllabus_id):
    """Delete syllabus entry"""
    try:
        admin_service.update_syllabus(syllabus_id, is_active=False)
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

# Timetable management routes
@app.route("/admin/timetable", methods=["GET"])
def admin_get_timetable():
    """Get all timetable entries"""
    try:
        timetable = admin_service.get_timetable()
        return jsonify({"success": True, "timetable": timetable})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/admin/timetable", methods=["POST"])
def admin_create_timetable():
    """Create new timetable entry"""
    try:
        data = request.json
        timetable_id = admin_service.create_timetable_entry(
            class_section=data.get("class_section"),
            day_of_week=data.get("day_of_week"),
            period_number=data.get("period_number"),
            start_time=data.get("start_time"),
            end_time=data.get("end_time"),
            subject=data.get("subject"),
            teacher_name=data.get("teacher_name"),
            room_number=data.get("room_number")
        )
        return jsonify({"success": True, "id": timetable_id})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/admin/timetable/<int:timetable_id>", methods=["DELETE"])
def admin_delete_timetable(timetable_id):
    """Delete timetable entry"""
    try:
        admin_service.delete_timetable_entry(timetable_id)
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

@app.route("/health")
def health():
    """Health check endpoint"""
    return jsonify({
        "status": "healthy", 
        "service": "ThutoAI Enhanced",
        "features": ["AI Chat", "School Integration", "Student Dashboard", "Admin Panel"]
    })

if __name__ == "__main__":
    # Initialize database with sample data
    try:
        from models import DatabaseManager
        db = DatabaseManager()
        db.add_sample_data()
        print("Database initialized with sample data")
    except Exception as e:
        print(f"Database initialization error: {e}")
    
    print("Starting ThutoAI Enhanced - Your Complete Student Assistant")
    print("Features: AI Chat + School Info + Student Dashboard + Admin Panel")
    print("Access at: http://0.0.0.0:7860")
    
    app.run(host="0.0.0.0", port=7860, debug=True)