File size: 142,032 Bytes
1ff4ed7
35cddd4
 
 
 
 
 
 
 
1ff4ed7
35cddd4
 
1ff4ed7
35cddd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed978d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35cddd4
ed978d2
 
 
 
 
 
 
 
 
 
 
 
 
35cddd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7d5393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09f0877
b868426
 
e7d5393
2016803
 
 
 
 
 
e7d5393
 
09f0877
b868426
2016803
 
 
 
 
 
 
 
e7d5393
09f0877
 
b868426
e7d5393
 
 
09f0877
 
 
2016803
e7d5393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a018390
2016803
e7d5393
 
 
 
 
a018390
2016803
e7d5393
 
 
a018390
2016803
e7d5393
 
 
a018390
2016803
e7d5393
 
 
a018390
2016803
e7d5393
 
 
 
 
 
2016803
 
 
e7d5393
35cddd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed978d2
 
 
 
 
 
 
 
 
 
 
 
 
 
35cddd4
ed978d2
 
 
 
 
 
 
 
 
 
 
 
 
35cddd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2f9ed8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d53784e
a2f9ed8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e41ec3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdef6ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b0fe6a
bdef6ae
3b0fe6a
bdef6ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b0fe6a
 
 
 
 
 
 
 
 
 
 
bdef6ae
3b0fe6a
 
bdef6ae
3b0fe6a
 
bdef6ae
3b0fe6a
 
 
 
 
 
 
 
 
 
a018390
 
3b0fe6a
a018390
3b0fe6a
 
a018390
3b0fe6a
2dc600e
91b7d07
a018390
 
 
 
3b0fe6a
91b7d07
a018390
 
 
 
 
 
91b7d07
 
 
 
 
 
 
a018390
2016803
a018390
2016803
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84bb726
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c37dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2016803
 
 
 
 
 
 
 
 
 
32c37dc
 
 
 
 
 
84bb726
 
 
 
 
 
2016803
84bb726
32c37dc
 
 
 
 
 
 
2016803
84bb726
 
2016803
 
 
 
 
84bb726
 
2016803
 
 
 
 
84bb726
 
 
 
2016803
84bb726
2016803
 
 
 
a018390
2016803
a018390
2016803
 
3e2a559
 
 
cb13103
7dc14dd
cb13103
 
 
7dc14dd
cb13103
7dc14dd
 
cb13103
7dc14dd
3e2a559
cb13103
 
3e2a559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dc14dd
 
 
3e2a559
 
cb13103
 
 
 
 
 
 
 
3e2a559
dd21ba1
 
 
ca03d2b
dd21ba1
2016803
dd21ba1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a018390
dd21ba1
2016803
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2f9ed8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d53784e
 
 
 
 
 
 
 
14fd00e
a2f9ed8
 
 
 
 
 
 
 
 
 
 
 
d53784e
a2f9ed8
d53784e
 
a2f9ed8
d53784e
a2f9ed8
 
 
 
 
 
 
 
 
 
 
14fd00e
a2f9ed8
14fd00e
a2f9ed8
 
 
 
 
 
 
 
 
 
 
 
 
 
14fd00e
a2f9ed8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14fd00e
a2f9ed8
 
 
35cddd4
 
 
 
 
 
ce7e441
35cddd4
91c4632
 
 
b81807f
91c4632
55884b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91c4632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56537f5
 
 
 
 
 
 
 
 
91c4632
 
 
 
 
 
56537f5
91c4632
56537f5
f10cfac
 
56537f5
 
 
f10cfac
 
 
f868e83
67e29ea
 
 
 
 
 
 
 
 
 
f868e83
 
 
f10cfac
 
929dd4e
 
 
 
 
 
 
 
 
 
 
f868e83
929dd4e
 
 
67e29ea
 
 
 
f868e83
 
f10cfac
 
67e29ea
 
 
 
f868e83
 
67e29ea
 
 
 
 
 
 
 
f868e83
 
67e29ea
 
929dd4e
 
 
 
 
 
 
 
 
f868e83
929dd4e
 
 
 
 
 
f868e83
929dd4e
 
67e29ea
 
 
f868e83
 
67e29ea
 
 
 
 
 
 
f868e83
 
 
67e29ea
 
 
 
 
 
f868e83
 
67e29ea
 
f868e83
67e29ea
 
 
 
f868e83
 
 
91c4632
 
929dd4e
 
 
 
f868e83
929dd4e
 
 
 
 
f868e83
929dd4e
 
 
 
 
 
 
 
 
 
 
f868e83
929dd4e
 
 
56537f5
 
 
91c4632
 
 
 
56537f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f10cfac
91c4632
 
56537f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ab1e60
 
 
 
 
 
 
 
 
67293ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ab1e60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe884cf
 
 
 
 
 
 
 
 
edd7688
 
 
 
 
 
 
 
 
 
fe884cf
 
edd7688
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88a32f
 
 
edd7688
 
 
67293ea
 
 
 
 
edd7688
 
 
 
 
67293ea
 
 
fe884cf
 
edd7688
8d93679
 
 
edd7688
 
8d93679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd7688
 
 
d88a32f
 
 
8d93679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd7688
 
fe884cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b03b98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe884cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71055c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67293ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd7688
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88a32f
 
 
edd7688
 
91c4632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153cfdb
91c4632
 
 
153cfdb
91c4632
 
 
a0b0638
91c4632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153cfdb
91c4632
 
 
 
 
 
 
 
 
153cfdb
91c4632
 
153cfdb
91c4632
 
 
 
 
 
 
 
 
 
 
71055c2
91c4632
 
 
 
 
 
 
 
 
71055c2
91c4632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35cddd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db88471
 
 
0cc1ca4
 
 
 
db88471
 
 
53ebb28
 
0cc1ca4
53ebb28
 
 
0cc1ca4
 
 
 
 
 
db88471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ebb28
 
db88471
53ebb28
 
 
db88471
 
 
 
 
 
 
a081fee
 
 
 
 
 
 
 
 
53ebb28
 
 
 
 
 
 
 
 
 
 
 
 
0204902
 
a081fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0204902
a081fee
 
 
0204902
 
 
 
a081fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0204902
 
a081fee
 
7cd64bd
0204902
7cd64bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ebb28
35cddd4
 
 
91c4632
35cddd4
 
91c4632
35cddd4
 
 
 
 
 
81771ac
a2f9ed8
 
91c4632
 
 
 
 
 
 
 
 
a2f9ed8
91c4632
 
 
 
a2f9ed8
 
 
 
 
 
 
 
 
 
 
 
 
 
91c4632
 
 
 
 
 
 
a2f9ed8
 
91c4632
a2f9ed8
91c4632
a2f9ed8
 
73164ee
91c4632
 
 
 
7df0325
a2f9ed8
 
91c4632
 
 
 
 
 
 
81771ac
 
 
91c4632
 
 
 
 
 
a2f9ed8
91c4632
 
 
a2f9ed8
db88471
 
0cc1ca4
 
0204902
 
a2f9ed8
 
91c4632
 
14fd00e
 
 
73164ee
14fd00e
 
81771ac
 
73164ee
081d73d
a2f9ed8
 
81771ac
 
46f9d98
41437ca
46f9d98
 
 
 
 
 
 
14fd00e
7d732ff
41437ca
 
 
 
 
 
7d732ff
41437ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81771ac
a2f9ed8
 
41437ca
 
 
 
 
0204902
41437ca
 
 
0204902
1aa95ae
a80be0a
 
9312362
2d2f7cb
a081fee
 
7cd64bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a081fee
7cd64bd
 
 
 
 
 
 
a081fee
 
 
 
9312362
a2f9ed8
41437ca
a2f9ed8
 
 
14fd00e
a2f9ed8
81771ac
a80be0a
a2f9ed8
 
 
46f9d98
81771ac
41437ca
a2f9ed8
 
 
 
41437ca
a2f9ed8
 
 
 
 
 
81771ac
a2f9ed8
 
f6b2867
 
 
91c4632
 
 
 
 
 
 
 
f6b2867
 
91c4632
bdecf43
 
f6b2867
 
 
91c4632
bdecf43
 
f6b2867
 
 
 
 
 
91c4632
f6b2867
 
 
91c4632
bdecf43
 
f6b2867
 
91c4632
 
 
f6b2867
 
91c4632
 
 
 
 
 
f6b2867
91c4632
 
 
 
 
 
 
 
 
 
f6b2867
 
 
 
 
 
 
 
 
91c4632
 
a372a30
 
 
 
 
 
 
 
e7d5393
f6b2867
e7d5393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19c3bee
e7d5393
 
 
 
 
 
 
 
 
 
 
 
a76910f
 
 
 
 
19c3bee
a76910f
 
 
 
 
 
19c3bee
a76910f
e7d5393
f6b2867
 
 
91c4632
 
 
 
 
 
 
 
f6b2867
 
91c4632
bdecf43
 
f6b2867
 
 
91c4632
bdecf43
 
f6b2867
 
 
 
 
 
91c4632
f6b2867
 
 
91c4632
f6b2867
 
 
91c4632
 
 
f6b2867
 
91c4632
 
 
 
 
 
f6b2867
91c4632
 
 
f6b2867
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35cddd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
import gradio as gr
import os
import json
import requests
import smtplib
import sqlite3
from datetime import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Get Hugging Face token from environment variable
HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN")

# Database configuration
DATABASE_FILE = "feedback.db"

# Email configuration (private)
FEEDBACK_EMAIL = "mahdi@brightmind-ai.com"
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
SMTP_USERNAME = os.getenv("SMTP_USERNAME", "")
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD", "")

# Debug token detection
print(f"πŸ” Token detection debug:")
print(f"   - HF_TOKEN exists: {HF_TOKEN is not None}")
print(f"   - HF_TOKEN length: {len(HF_TOKEN) if HF_TOKEN else 0}")
print(f"   - HF_TOKEN starts with hf_: {HF_TOKEN.startswith('hf_') if HF_TOKEN else False}")
print(f"   - SMTP configured: {SMTP_USERNAME != '' and SMTP_PASSWORD != ''}")

def generate_lesson_plan_with_progress(topic, subject, grade_level, duration, difficulty="intermediate"):
    """Generate a lesson plan with progress updates"""
    
    # Show progress bar
    progress_html = """
    <div class="progress-container">
        <div class="generation-status">πŸ€– Generating your lesson plan...</div>
        <div class="progress-bar">
            <div class="progress-fill"></div>
        </div>
        <div class="generation-status">Analyzing requirements and creating content...</div>
    </div>
    """
    
    yield progress_html, ""
    
    print(f"πŸš€ Starting lesson plan generation for: {topic}")
    print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Duration: {duration}min")
    
    # Try Hugging Face API first if token is available
    if HF_TOKEN:
        print("πŸ€– Token found! Attempting Hugging Face API call...")
        try:
            prompt = f"""Create a comprehensive lesson plan for:
Topic: {topic}
Subject: {subject}
Grade Level: {grade_level}
Duration: {duration} minutes
Difficulty: {difficulty}

Include:
1. Learning objectives
2. Activities with time allocations
3. Materials needed
4. Assessment methods
5. Differentiation strategies
6. Educational standards
7. Real-world connections
8. Extension activities

Make it practical, engaging, and ready for classroom use."""

            result = call_hugging_face_api_content(prompt)
            
            if result:
                print("βœ… Successfully generated with Hugging Face API")
                
                # Show completion and return result
                completion_html = """
                <div class="progress-container">
                    <div class="generation-status">βœ… Lesson Plan Generated Successfully!</div>
                </div>
                """
                yield completion_html, result
            else:
                print("❌ API call returned no content, falling back to algorithms")
                raise Exception("No content returned from API")
            
        except Exception as e:
            print(f"❌ Hugging Face API failed: {e}")
            print("πŸ”„ Falling back to educational algorithms...")
            
            # Show fallback progress
            fallback_html = """
            <div class="progress-container">
                <div class="generation-status">πŸ”„ Using educational algorithms...</div>
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
            </div>
            """
            yield fallback_html, ""
            
            result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
            print("βœ… Generated with educational algorithms")
            
            # Show completion
            completion_html = """
            <div class="progress-container">
                <div class="generation-status">βœ… Lesson Plan Generated with Educational Algorithms!</div>
            </div>
            """
            yield completion_html, result
    else:
        print("⚠️ No Hugging Face token found, using educational algorithms...")
        
        # Show progress for algorithms
        algo_html = """
        <div class="progress-container">
            <div class="generation-status">πŸ“š Using educational algorithms...</div>
            <div class="progress-bar">
                <div class="progress-fill"></div>
            </div>
        </div>
        """
        yield algo_html, ""
        
        result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
        print("βœ… Generated with educational algorithms")
        
        # Show completion
        completion_html = """
        <div class="progress-container">
            <div class="generation-status">βœ… Lesson Plan Generated Successfully!</div>
        </div>
        """
        yield completion_html, result

def generate_lesson_plan(topic, subject, grade_level, duration, difficulty="intermediate"):
    """Generate a lesson plan using Hugging Face API or fallback algorithms"""
    
    print(f"πŸš€ Starting lesson plan generation for: {topic}")
    print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Duration: {duration}min")
    
    # Try Hugging Face API first if token is available
    if HF_TOKEN:
        print("πŸ€– Token found! Attempting Hugging Face API call...")
        try:
            result = generate_with_hugging_face(topic, subject, grade_level, duration, difficulty)
            print("βœ… Successfully generated with Hugging Face API")
            return result
        except Exception as e:
            print(f"❌ Hugging Face API failed: {e}")
            print("πŸ”„ Falling back to educational algorithms...")
    else:
        print("⚠️ No Hugging Face token found, using educational algorithms...")
    
    # Fallback to educational algorithms
    result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
    print("βœ… Generated with educational algorithms")
    return result

def typewriter_effect(text, status_message):
    """Create typewriter effect for displaying content"""
    import time
    
    # Show typewriter container
    typewriter_html = f"""
    <div class="typewriter-container">
        <div class="typewriter-header">
            <span class="book-icon">πŸ“–</span>
            <span class="generation-status">{status_message}</span>
        </div>
        <div class="typewriter-text" id="typewriter-content">
        </div>
    </div>
    """
    
    yield typewriter_html, ""
    
    # Typewriter effect
    displayed_text = ""
    for i, char in enumerate(text):
        displayed_text += char
        if char == '\n':
            displayed_text += "  "  # Add indentation for new lines
        
        # Update the content
        updated_html = f"""
        <div class="typewriter-container">
            <div class="typewriter-header">
                <span class="book-icon">πŸ“–</span>
                <span class="generation-status">{status_message}</span>
            </div>
            <div class="typewriter-text">
                {displayed_text}<span class="cursor">|</span>
            </div>
        </div>
        """
        
        yield updated_html, ""
        time.sleep(0.02)  # Adjust speed here
    
    # Final result without cursor - just return the text content
    yield "", text

def generate_content_with_progress(topic, subject, grade_level, difficulty, content_type, content_length):
    """Generate educational content with progress updates"""
    
    # Show progress bar
    progress_html = """
    <div class="progress-container">
        <div class="generation-status">πŸ“ Generating your educational content...</div>
        <div class="progress-bar">
            <div class="progress-fill"></div>
        </div>
        <div class="generation-status">Creating materials tailored to your specifications...</div>
    </div>
    """
    
    yield progress_html, ""
    
    print(f"πŸš€ Starting content generation for: {topic}")
    print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Type: {content_type}")
    
    # Try Hugging Face API first if token is available
    if HF_TOKEN:
        print("πŸ€– Token found! Attempting Hugging Face API call for content generation...")
        print(f"πŸ”‘ Token length: {len(HF_TOKEN)}")
        print(f"πŸ”‘ Token starts with hf_: {HF_TOKEN.startswith('hf_')}")
        try:
            # Use the enhanced content agent
            print("🎨 Creating content generation agent...")
            agent_prompt = create_content_agent(topic, subject, grade_level, difficulty, content_type, content_length)
            
            print(f"πŸ“ Sending agent prompt to API...")
            ai_content = call_hugging_face_api_content(agent_prompt)
            
            if ai_content:
                print("βœ… Content generation API call successful!")
                print(f"πŸ“„ Generated content length: {len(ai_content)} characters")
                
                # Process content with image placeholders and multimedia
                print("πŸ–ΌοΈ Processing content with multimedia elements...")
                enhanced_content = process_content_with_images(ai_content, topic, content_type)
                
                print(f"πŸ“„ Enhanced content length: {len(enhanced_content)} characters")
                print(f"πŸ“„ First 200 chars: {enhanced_content[:200]}...")
                yield "", enhanced_content
                return
            else:
                print("❌ Content generation API call returned no content")
                print("πŸ”„ Falling back to template content...")
        except Exception as e:
            print(f"❌ Content generation API error: {str(e)}")
    
    else:
        print("❌ No HF_TOKEN available for content generation")
    
    # Fallback content with image placeholders
    fallback_content = f"""# {content_type}: {topic}

## Learning Objectives
By the end of this {content_type.lower()}, students will be able to:
- Understand the basic concepts of {topic}
- Apply knowledge through practical exercises
- Demonstrate comprehension through assessment

## Grade Level: {grade_level}
## Subject: {subject}
## Difficulty: {difficulty}

---

## Introduction
This {content_type.lower()} is designed for {grade_level} students studying {subject}. The content focuses on {topic} at a {difficulty.lower()} level.

{generate_real_image(f"Visual introduction to {topic} concepts", topic, content_type)}

## Main Content

### Section 1: Understanding {topic}
[Content will be generated based on the specific topic and grade level]

{generate_real_image(f"Diagram showing {topic} key concepts", topic, content_type)}

### Section 2: Practical Applications
[Real-world examples and applications]

{generate_real_image(f"Real-world examples of {topic} in action", topic, content_type)}

### Section 3: Activities and Exercises
[Hands-on activities appropriate for {grade_level}]

{generate_real_image(f"Step-by-step activity instructions for {topic}", topic, content_type)}

## Assessment
[Questions and exercises to test understanding]

{generate_real_image(f"Visual assessment rubric for {topic}", topic, content_type)}

## Additional Resources
[Links and references for further learning]

---
*Generated for {grade_level} {subject} students - {difficulty} level*"""

    # Process fallback content with multimedia elements
    enhanced_fallback = process_content_with_images(fallback_content, topic, content_type)
    yield "", enhanced_fallback

def generate_quiz_with_progress(topic, subject, grade_level, question_count, question_types):
    """Generate a quiz with progress updates"""
    
    # Show progress bar
    progress_html = """
    <div class="progress-container">
        <div class="generation-status">🎯 Generating your quiz...</div>
        <div class="progress-bar">
            <div class="progress-fill"></div>
        </div>
        <div class="generation-status">Creating questions and answers...</div>
    </div>
    """
    
    yield progress_html, ""
    
    print(f"🎯 Starting quiz generation for: {topic}")
    print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Questions: {question_count}")
    print(f"πŸ“ Question types: {', '.join(question_types)}")
    
    # Try Hugging Face API first if token is available
    if HF_TOKEN:
        print("πŸ€– Token found! Attempting Hugging Face API call for quiz...")
        try:
            prompt = f"""Create a comprehensive quiz about "{topic}" for {grade_level} students studying {subject}.

Requirements:
- Generate exactly {question_count} questions
- Include these question types: {', '.join(question_types)}
- Make questions appropriate for {grade_level} grade level
- Ensure questions are specific to "{topic}"
- Include correct answers and explanations
- Format as a structured quiz with clear questions, options, and explanations
- Make it engaging and educational

Format the response as a structured quiz with clear questions, options, and explanations."""

            result = call_hugging_face_api_content(prompt)
            
            if result:
                print("βœ… Successfully generated quiz with Hugging Face API")
                
                # Show completion and return result
                completion_html = """
                <div class="progress-container">
                    <div class="generation-status">βœ… Quiz Generated Successfully!</div>
                </div>
                """
                yield completion_html, result
            else:
                print("❌ API call returned no content, falling back to algorithms")
                raise Exception("No content returned from API")
            
        except Exception as e:
            print(f"❌ Hugging Face API failed: {e}")
            print("πŸ”„ Falling back to educational algorithms...")
            
            # Show fallback progress
            fallback_html = """
            <div class="progress-container">
                <div class="generation-status">πŸ”„ Using educational algorithms...</div>
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
            </div>
            """
            yield fallback_html, ""
            
            result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
            print("βœ… Generated quiz with educational algorithms")
            
            # Show completion
            completion_html = """
            <div class="progress-container">
                <div class="generation-status">βœ… Quiz Generated with Educational Algorithms!</div>
            </div>
            """
            yield completion_html, result
    else:
        print("⚠️ No Hugging Face token found, using educational algorithms...")
        
        # Show progress for algorithms
        algo_html = """
        <div class="progress-container">
            <div class="generation-status">🎯 Using educational algorithms...</div>
            <div class="progress-bar">
                <div class="progress-fill"></div>
            </div>
        </div>
        """
        yield algo_html, ""
        
        result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
        print("βœ… Generated quiz with educational algorithms")
        
        # Show completion
        completion_html = """
        <div class="progress-container">
            <div class="generation-status">βœ… Quiz Generated Successfully!</div>
        </div>
        """
        yield completion_html, result

def generate_quiz(topic, subject, grade_level, question_count, question_types):
    """Generate a quiz using Hugging Face API or fallback algorithms"""
    
    print(f"🎯 Starting quiz generation for: {topic}")
    print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Questions: {question_count}")
    print(f"πŸ“ Question types: {', '.join(question_types)}")
    
    # Try Hugging Face API first if token is available
    if HF_TOKEN:
        print("πŸ€– Token found! Attempting Hugging Face API call for quiz...")
        try:
            result = generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types)
            print("βœ… Successfully generated quiz with Hugging Face API")
            return result
        except Exception as e:
            print(f"❌ Hugging Face API failed: {e}")
            print("πŸ”„ Falling back to educational algorithms...")
    else:
        print("⚠️ No Hugging Face token found, using educational algorithms...")
    
    # Fallback to educational algorithms
    result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
    print("βœ… Generated quiz with educational algorithms")
    return result

def generate_with_hugging_face(topic, subject, grade_level, duration, difficulty):
    """Generate lesson plan using Hugging Face Inference Providers API"""
    
    print(f"🌐 Making API call to Hugging Face Inference Providers...")
    print(f"πŸ”— Endpoint: https://router.huggingface.co/v1/chat/completions")
    print(f"πŸ”‘ Token available: {HF_TOKEN is not None}")
    
    prompt = f"""Create a comprehensive lesson plan for:
Topic: {topic}
Subject: {subject}
Grade Level: {grade_level}
Duration: {duration} minutes
Difficulty: {difficulty}

Include:
1. Learning objectives
2. Activities with time allocations
3. Materials needed
4. Assessment methods
5. Differentiation strategies
6. Educational standards

Format as a structured lesson plan."""

    print(f"πŸ“ Prompt length: {len(prompt)}")

    headers = {
        "Authorization": f"Bearer {HF_TOKEN}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "deepseek-ai/DeepSeek-V3-0324",
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": 1000,
        "temperature": 0.7
    }
    
    print(f"πŸ“‘ Sending API request...")
    try:
        response = requests.post(
            "https://router.huggingface.co/v1/chat/completions",
            headers=headers,
            json=data,
            timeout=30
        )
        
        print(f"πŸ“‘ API Response Status: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print(f"βœ… API Response received: {type(result)}")
            print(f"πŸ“„ Response content length: {len(str(result))}")
            
            if "choices" in result and len(result["choices"]) > 0:
                content = result["choices"][0]["message"]["content"]
            else:
                content = ""
            
            print(f"πŸ“ Generated content length: {len(content)}")
            
            if content and len(content) > 50:  # Ensure we got meaningful content
                return format_lesson_plan(content, topic, subject, grade_level, duration, True)
            else:
                print("⚠️ API returned empty or too short content, falling back to algorithms")
                raise Exception("Empty or insufficient content from API")
        else:
            error_text = response.text
            print(f"❌ API Error: {response.status_code} - {error_text}")
            raise Exception(f"API request failed: {response.status_code} - {error_text}")
            
    except requests.exceptions.Timeout:
        print("⏰ API request timed out, falling back to algorithms")
        raise Exception("API request timeout")
    except requests.exceptions.RequestException as e:
        print(f"🌐 Network error: {e}, falling back to algorithms")
        raise Exception(f"Network error: {e}")
    except Exception as e:
        print(f"❌ Unexpected error: {e}, falling back to algorithms")
        raise Exception(f"Unexpected error: {e}")

def generate_with_algorithms(topic, subject, grade_level, duration, difficulty):
    """Generate lesson plan using educational algorithms"""
    
    grade = int(grade_level.split('-')[0]) if '-' in grade_level else int(grade_level)
    
    # Generate objectives based on Bloom's Taxonomy
    objectives = generate_objectives(topic, grade)
    
    # Generate activities
    activities = generate_activities(topic, int(duration), grade)
    
    # Generate materials
    materials = generate_materials(subject, grade)
    
    # Generate assessment
    assessment = generate_assessment(grade)
    
    # Generate differentiation
    differentiation = generate_differentiation()
    
    lesson_plan = {
        "topic": topic,
        "subject": subject,
        "grade_level": grade_level,
        "duration": duration,
        "difficulty": difficulty,
        "objectives": objectives,
        "activities": activities,
        "materials": materials,
        "assessment": assessment,
        "differentiation": differentiation,
        "ai_generated": False,
        "generated_at": datetime.now().strftime("%Y-%m-%d")
    }
    
    return format_lesson_plan_from_dict(lesson_plan)

def generate_objectives(topic, grade):
    """Generate learning objectives based on grade level"""
    if grade <= 2:
        return [
            f"Students will identify key concepts about {topic}",
            f"Students will demonstrate understanding through hands-on activities"
        ]
    elif grade <= 5:
        return [
            f"Students will explain the main concepts of {topic}",
            f"Students will apply knowledge through practical exercises",
            f"Students will analyze information about {topic}"
        ]
    elif grade <= 8:
        return [
            f"Students will analyze and evaluate information about {topic}",
            f"Students will synthesize knowledge through creative projects",
            f"Students will demonstrate critical thinking skills"
        ]
    else:
        return [
            f"Students will critically analyze complex concepts in {topic}",
            f"Students will synthesize information from multiple sources",
            f"Students will create original work demonstrating mastery"
        ]

def generate_activities(topic, duration, grade):
    """Generate activities with time allocations"""
    activities = []
    
    # Introduction (15% of time)
    intro_time = max(5, int(duration * 0.15))
    activities.append({
        "name": f"Introduction to {topic}",
        "duration": f"{intro_time} minutes",
        "description": f"Engage students with a hook activity related to {topic}"
    })
    
    # Main activities (60% of time)
    main_time = int(duration * 0.6)
    if grade <= 2:
        activities.append({
            "name": "Hands-on Exploration",
            "duration": f"{main_time} minutes",
            "description": f"Interactive exploration of {topic} through manipulatives and visual aids"
        })
    elif grade <= 5:
        activities.append({
            "name": "Guided Discovery",
            "duration": f"{int(main_time * 0.6)} minutes",
            "description": f"Structured exploration of {topic} with teacher guidance"
        })
        activities.append({
            "name": "Collaborative Learning",
            "duration": f"{int(main_time * 0.4)} minutes",
            "description": f"Group work to deepen understanding of {topic}"
        })
    else:
        activities.append({
            "name": "Independent Research",
            "duration": f"{int(main_time * 0.4)} minutes",
            "description": f"Students research aspects of {topic} independently"
        })
        activities.append({
            "name": "Discussion and Analysis",
            "duration": f"{int(main_time * 0.6)} minutes",
            "description": f"Class discussion analyzing different perspectives on {topic}"
        })
    
    # Practice (20% of time)
    practice_time = int(duration * 0.2)
    activities.append({
        "name": "Practice and Application",
        "duration": f"{practice_time} minutes",
        "description": f"Students apply their knowledge through exercises related to {topic}"
    })
    
    return activities

def generate_materials(subject, grade):
    """Generate materials based on subject and grade"""
    materials = ["Whiteboard or chart paper", "Markers or chalk"]
    
    if grade <= 2:
        materials.extend(["Visual aids and pictures", "Manipulatives or hands-on objects", "Colored pencils and paper"])
    elif grade <= 5:
        materials.extend(["Textbooks or reference materials", "Worksheets or activity sheets", "Art supplies for projects"])
    elif grade <= 8:
        materials.extend(["Research materials (books, articles)", "Technology devices (if available)", "Presentation materials"])
    else:
        materials.extend(["Advanced reference materials", "Technology for research and presentation", "Writing materials for essays or reports"])
    
    # Subject-specific materials
    if subject.lower() == "science":
        materials.extend(["Science equipment or models", "Safety materials (if needed)"])
    elif subject.lower() == "math":
        materials.extend(["Calculators (if appropriate)", "Graph paper or rulers"])
    elif subject.lower() == "history":
        materials.extend(["Historical documents or primary sources", "Maps or timelines"])
    
    return materials

def generate_assessment(grade):
    """Generate assessment methods based on grade level"""
    if grade <= 2:
        return ["Observation of student participation", "Simple oral questions and answers", "Drawing or visual representation of learning"]
    elif grade <= 5:
        return ["Quick quiz or exit ticket", "Student presentations or demonstrations", "Portfolio of completed work"]
    elif grade <= 8:
        return ["Written reflection or journal entry", "Group project evaluation", "Peer assessment activities"]
    else:
        return ["Essay or written analysis", "Research project presentation", "Peer review and self-assessment"]

def generate_differentiation():
    """Generate differentiation strategies"""
    return {
        "struggling": [
            "Provide additional visual aids and examples",
            "Break down complex concepts into smaller parts",
            "Offer one-on-one support during activities",
            "Use simplified language and vocabulary"
        ],
        "advanced": [
            "Provide extension activities and challenges",
            "Encourage independent research and exploration",
            "Assign leadership roles in group activities",
            "Offer opportunities for creative expression"
        ],
        "ell": [
            "Use visual supports and gestures",
            "Provide vocabulary lists and definitions",
            "Pair with native speakers for support",
            "Use multimedia resources when available"
        ]
    }

def format_lesson_plan(content, topic, subject, grade_level, duration, ai_generated):
    """Format lesson plan from AI response"""
    return f"""
# Lesson Plan: {topic}

**Subject:** {subject}  
**Grade Level:** {grade_level}  
**Duration:** {duration} minutes  
**Generated:** {datetime.now().strftime("%Y-%m-%d")}  
**AI Generated:** {'Yes' if ai_generated else 'No'}

---

## Content

{content}

---

*Generated by BrightMind AI - Educational Technology Platform*
"""

def format_lesson_plan_from_dict(lesson_plan):
    """Format lesson plan from dictionary"""
    content = f"""
# Lesson Plan: {lesson_plan['topic']}

**Subject:** {lesson_plan['subject']}  
**Grade Level:** {lesson_plan['grade_level']}  
**Duration:** {lesson_plan['duration']} minutes  
**Difficulty:** {lesson_plan['difficulty']}  
**Generated:** {lesson_plan['generated_at']}  
**AI Generated:** {'Yes' if lesson_plan['ai_generated'] else 'No'}

---

## Learning Objectives

"""
    
    for i, objective in enumerate(lesson_plan['objectives'], 1):
        content += f"{i}. {objective}\n"
    
    content += "\n## Activities\n\n"
    for activity in lesson_plan['activities']:
        content += f"**{activity['name']}** ({activity['duration']})\n"
        content += f"{activity['description']}\n\n"
    
    content += "## Materials Needed\n\n"
    for material in lesson_plan['materials']:
        content += f"β€’ {material}\n"
    
    content += "\n## Assessment Methods\n\n"
    for i, assessment in enumerate(lesson_plan['assessment'], 1):
        content += f"{i}. {assessment}\n"
    
    content += "\n## Differentiation Strategies\n\n"
    for category, strategies in lesson_plan['differentiation'].items():
        content += f"**{category.title()} Learners:**\n"
        for strategy in strategies:
            content += f"β€’ {strategy}\n"
        content += "\n"
    
    content += "\n---\n*Generated by BrightMind AI - Educational Technology Platform*"
    
    return content

def generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types):
    """Generate quiz using Hugging Face Inference Providers API"""
    
    print(f"🌐 Making API call to Hugging Face Inference Providers for quiz...")
    print(f"πŸ”— Endpoint: https://router.huggingface.co/v1/chat/completions")
    print(f"πŸ”‘ Token available: {HF_TOKEN is not None}")
    
    prompt = f"""Create a quiz about "{topic}" for {grade_level} students studying {subject}.

Requirements:
- Generate exactly {question_count} questions
- Include these question types: {', '.join(question_types)}
- Make questions appropriate for {grade_level} grade level
- Ensure questions are specific to "{topic}"
- Include correct answers and explanations

Format the response as a structured quiz with clear questions, options, and explanations."""

    print(f"πŸ“ Prompt length: {len(prompt)}")

    headers = {
        "Authorization": f"Bearer {HF_TOKEN}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "deepseek-ai/DeepSeek-V3-0324",
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": 1000,
        "temperature": 0.7
    }
    
    print(f"πŸ“‘ Sending API request...")
    try:
        response = requests.post(
            "https://router.huggingface.co/v1/chat/completions",
            headers=headers,
            json=data,
            timeout=30
        )
        
        print(f"πŸ“‘ API Response Status: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print(f"βœ… API Response received: {type(result)}")
            print(f"πŸ“„ Response content length: {len(str(result))}")
            
            if "choices" in result and len(result["choices"]) > 0:
                content = result["choices"][0]["message"]["content"]
            else:
                content = ""
            
            print(f"πŸ“ Generated content length: {len(content)}")
            
            if content and len(content) > 50:  # Ensure we got meaningful content
                return format_quiz(content, topic, subject, grade_level, question_count, True)
            else:
                print("⚠️ API returned empty or too short content, falling back to algorithms")
                raise Exception("Empty or insufficient content from API")
        else:
            error_text = response.text
            print(f"❌ API Error: {response.status_code} - {error_text}")
            raise Exception(f"API request failed: {response.status_code} - {error_text}")
            
    except requests.exceptions.Timeout:
        print("⏰ API request timed out, falling back to algorithms")
        raise Exception("API request timeout")
    except requests.exceptions.RequestException as e:
        print(f"🌐 Network error: {e}, falling back to algorithms")
        raise Exception(f"Network error: {e}")
    except Exception as e:
        print(f"❌ Unexpected error: {e}, falling back to algorithms")
        raise Exception(f"Unexpected error: {e}")

def generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types):
    """Generate quiz using educational algorithms"""
    
    questions = []
    grade = int(grade_level.split('-')[0]) if '-' in grade_level else int(grade_level)
    
    for i in range(int(question_count)):
        question_type = question_types[i % len(question_types)]
        question = generate_question_by_type(question_type, topic, subject, grade, i + 1)
        questions.append(question)
    
    quiz = {
        "topic": topic,
        "subject": subject,
        "grade_level": grade_level,
        "question_count": int(question_count),
        "questions": questions,
        "generated_at": datetime.now().strftime("%Y-%m-%d"),
        "ai_generated": False
    }
    
    return format_quiz_from_dict(quiz)

def generate_question_by_type(question_type, topic, subject, grade, question_number):
    """Generate a specific type of question"""
    
    if question_type == "Multiple Choice":
        return generate_multiple_choice_question(topic, subject, grade, question_number)
    elif question_type == "True/False":
        return generate_true_false_question(topic, subject, grade, question_number)
    elif question_type == "Short Answer":
        return generate_short_answer_question(topic, subject, grade, question_number)
    elif question_type == "Fill in the Blank":
        return generate_fill_in_blank_question(topic, subject, grade, question_number)
    else:
        return generate_multiple_choice_question(topic, subject, grade, question_number)

def generate_multiple_choice_question(topic, subject, grade, question_number):
    """Generate a multiple choice question"""
    
    templates = [
        {
            "question": f"What is the main concept of {topic}?",
            "options": [
                f"A fundamental principle in {subject}",
                "A type of animal",
                "A mathematical formula",
                "A historical event"
            ],
            "correct": "A",
            "explanation": f"This question tests basic understanding of {topic} in the context of {subject}."
        },
        {
            "question": f"Which of the following best describes {topic}?",
            "options": [
                "A complex system with multiple components",
                "A simple process with one step",
                "A type of building material",
                "A musical instrument"
            ],
            "correct": "A",
            "explanation": f"{topic} involves multiple interconnected elements that work together."
        },
        {
            "question": f"How does {topic} relate to {subject}?",
            "options": [
                f"It provides a foundation for understanding {subject} concepts",
                "It is unrelated to the subject",
                "It only applies to advanced students",
                "It is only theoretical"
            ],
            "correct": "A",
            "explanation": f"{topic} helps students understand broader concepts in {subject}."
        }
    ]
    
    template = templates[question_number % len(templates)]
    return {
        "type": "Multiple Choice",
        "question": template["question"],
        "options": template["options"],
        "correct_answer": template["correct"],
        "explanation": template["explanation"]
    }

def generate_true_false_question(topic, subject, grade, question_number):
    """Generate a true/false question"""
    
    templates = [
        {
            "question": f"{topic} is an important concept in {subject}.",
            "correct": "True",
            "explanation": f"{topic} is indeed a fundamental concept in {subject} that students need to understand."
        },
        {
            "question": f"{topic} can only be learned through memorization.",
            "correct": "False",
            "explanation": f"{topic} is best learned through understanding, practice, and application, not just memorization."
        },
        {
            "question": f"Understanding {topic} helps students in other areas of {subject}.",
            "correct": "True",
            "explanation": f"Knowledge of {topic} provides a foundation for understanding related concepts in {subject}."
        }
    ]
    
    template = templates[question_number % len(templates)]
    return {
        "type": "True/False",
        "question": template["question"],
        "correct_answer": template["correct"],
        "explanation": template["explanation"]
    }

def generate_short_answer_question(topic, subject, grade, question_number):
    """Generate a short answer question"""
    
    templates = [
        {
            "question": f"Explain what {topic} means in your own words.",
            "correct_answer": f"Student should demonstrate understanding of {topic} concepts",
            "explanation": f"This question allows students to express their understanding of {topic} in their own words."
        },
        {
            "question": f"How does {topic} relate to {subject}?",
            "correct_answer": f"Student should explain the connection between {topic} and {subject}",
            "explanation": f"This question tests students' ability to make connections between concepts."
        },
        {
            "question": f"What are the key components of {topic}?",
            "correct_answer": f"Student should identify the main elements of {topic}",
            "explanation": f"This question tests students' ability to break down complex concepts."
        }
    ]
    
    template = templates[question_number % len(templates)]
    return {
        "type": "Short Answer",
        "question": template["question"],
        "correct_answer": template["correct_answer"],
        "explanation": template["explanation"]
    }

def generate_fill_in_blank_question(topic, subject, grade, question_number):
    """Generate a fill in the blank question"""
    
    templates = [
        {
            "question": f"{topic} is important because it helps us understand ______.",
            "correct_answer": f"{subject} concepts",
            "explanation": f"{topic} provides a foundation for understanding broader {subject} concepts."
        },
        {
            "question": f"The main purpose of {topic} is to ______.",
            "correct_answer": f"enhance learning in {subject}",
            "explanation": f"{topic} serves to improve students' understanding of {subject}."
        },
        {
            "question": f"Students learn {topic} to better understand ______.",
            "correct_answer": f"complex {subject} concepts",
            "explanation": f"{topic} helps students grasp more advanced {subject} topics."
        }
    ]
    
    template = templates[question_number % len(templates)]
    return {
        "type": "Fill in the Blank",
        "question": template["question"],
        "correct_answer": template["correct_answer"],
        "explanation": template["explanation"]
    }

def format_quiz(content, topic, subject, grade_level, question_count, ai_generated):
    """Format quiz from AI response"""
    return f"""
# Quiz: {topic}

**Subject:** {subject}  
**Grade Level:** {grade_level}  
**Questions:** {question_count}  
**Generated:** {datetime.now().strftime("%Y-%m-%d")}  
**AI Generated:** {'Yes' if ai_generated else 'No'}

---

## Quiz Content

{content}

---

*Generated by BrightMind AI - Educational Technology Platform*
"""

def format_quiz_from_dict(quiz):
    """Format quiz from dictionary"""
    content = f"""
# Quiz: {quiz['topic']}

**Subject:** {quiz['subject']}  
**Grade Level:** {quiz['grade_level']}  
**Questions:** {quiz['question_count']}  
**Generated:** {quiz['generated_at']}  
**AI Generated:** {'Yes' if quiz['ai_generated'] else 'No'}

---

## Questions

"""
    
    for i, question in enumerate(quiz['questions'], 1):
        content += f"### Question {i}: {question['type']}\n\n"
        content += f"**{question['question']}**\n\n"
        
        if question['type'] == 'Multiple Choice':
            for j, option in enumerate(question['options']):
                content += f"{chr(65 + j)}. {option}\n"
            content += f"\n**Correct Answer:** {question['correct_answer']}\n\n"
        elif question['type'] == 'True/False':
            content += f"**Answer:** {question['correct_answer']}\n\n"
        elif question['type'] == 'Short Answer':
            content += f"**Expected Answer:** {question['correct_answer']}\n\n"
        elif question['type'] == 'Fill in the Blank':
            content += f"**Answer:** {question['correct_answer']}\n\n"
        
        content += f"**Explanation:** {question['explanation']}\n\n"
        content += "---\n\n"
    
    content += "\n*Generated by BrightMind AI - Educational Technology Platform*"
    
    return content

def send_feedback_email(feedback_type, rating, comments, user_email=""):
    """Send feedback email to admin"""
    
    if not SMTP_USERNAME or not SMTP_PASSWORD:
        print("⚠️ SMTP credentials not configured, storing feedback locally")
        # Store feedback locally if no email configured
        feedback_data = {
            "timestamp": datetime.now().isoformat(),
            "feedback_type": feedback_type,
            "rating": rating,
            "comments": comments,
            "user_email": user_email
        }
        
        # Save to local file
        try:
            with open("feedback_log.json", "a") as f:
                f.write(json.dumps(feedback_data) + "\n")
            return "βœ… Feedback saved successfully! (Email not configured)"
        except Exception as e:
            return f"❌ Error saving feedback: {str(e)}"
    
    try:
        # Create message
        msg = MIMEMultipart()
        msg['From'] = SMTP_USERNAME
        msg['To'] = FEEDBACK_EMAIL
        msg['Subject'] = f"BrightMind AI Feedback - {feedback_type}"
        
        # Create email body
        body = f"""
        New Feedback Received from BrightMind AI Platform
        
        Feedback Type: {', '.join(feedback_type) if isinstance(feedback_type, list) else feedback_type}
        Rating: {rating}/5
        User Email: {user_email if user_email else 'Not provided'}
        Comments: {comments}
        
        Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        
        ---
        This feedback was automatically sent from the BrightMind AI platform.
        """
        
        msg.attach(MIMEText(body, 'plain'))
        
        # Send email
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()
        server.login(SMTP_USERNAME, SMTP_PASSWORD)
        text = msg.as_string()
        server.sendmail(SMTP_USERNAME, FEEDBACK_EMAIL, text)
        server.quit()
        
        print(f"βœ… Feedback email sent successfully to {FEEDBACK_EMAIL}")
        return "βœ… Thank you! Your feedback has been sent successfully."
        
    except Exception as e:
        print(f"❌ Error sending feedback email: {str(e)}")
        return f"❌ Error sending feedback: {str(e)}"

def submit_feedback(feedback_type, rating, comments, user_email):
    """Handle feedback submission"""
    
    if not feedback_type:
        return "❌ Please select at least one feedback type."
    
    if not rating:
        return "❌ Please provide a rating."
    
    if not comments.strip():
        return "❌ Please provide your comments."
    
    # Save to database first
    db_success = save_feedback_to_db(feedback_type, rating, comments, user_email)
    
    if not db_success:
        return "❌ Error saving feedback to database. Please try again."
    
    # Try to send email (optional)
    email_result = send_feedback_email(feedback_type, rating, comments, user_email)
    
    if "βœ…" in email_result:
        return "βœ… Thank you! Your feedback has been saved and sent successfully."
    else:
        return "βœ… Thank you! Your feedback has been saved successfully. (Email notification not available)"

def init_database():
    """Initialize the SQLite database"""
    try:
        conn = sqlite3.connect(DATABASE_FILE)
        cursor = conn.cursor()
        
        # Create feedback table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS feedback (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                feedback_type TEXT NOT NULL,
                rating INTEGER NOT NULL,
                comments TEXT NOT NULL,
                user_email TEXT,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        conn.commit()
        conn.close()
        print("βœ… Database initialized successfully")
        return True
    except Exception as e:
        print(f"❌ Database initialization error: {e}")
        return False

def save_feedback_to_db(feedback_type, rating, comments, user_email=""):
    """Save feedback to SQLite database"""
    try:
        conn = sqlite3.connect(DATABASE_FILE)
        cursor = conn.cursor()
        
        # Convert feedback_type list to string
        feedback_type_str = ', '.join(feedback_type) if isinstance(feedback_type, list) else str(feedback_type)
        
        cursor.execute('''
            INSERT INTO feedback (timestamp, feedback_type, rating, comments, user_email)
            VALUES (?, ?, ?, ?, ?)
        ''', (
            datetime.now().isoformat(),
            feedback_type_str,
            rating,
            comments,
            user_email
        ))
        
        conn.commit()
        conn.close()
        print("βœ… Feedback saved to database successfully")
        return True
    except Exception as e:
        print(f"❌ Database save error: {e}")
        return False

def get_feedback_stats():
    """Get feedback statistics for admin"""
    try:
        conn = sqlite3.connect(DATABASE_FILE)
        cursor = conn.cursor()
        
        # Get total feedback count
        cursor.execute('SELECT COUNT(*) FROM feedback')
        total_feedback = cursor.fetchone()[0]
        
        # Get average rating
        cursor.execute('SELECT AVG(rating) FROM feedback')
        avg_rating = cursor.fetchone()[0]
        avg_rating = round(avg_rating, 2) if avg_rating else 0
        
        # Get recent feedback (last 5)
        cursor.execute('''
            SELECT timestamp, feedback_type, rating, comments, user_email 
            FROM feedback 
            ORDER BY created_at DESC 
            LIMIT 5
        ''')
        recent_feedback = cursor.fetchall()
        
        conn.close()
        
        return {
            'total_feedback': total_feedback,
            'avg_rating': avg_rating,
            'recent_feedback': recent_feedback
        }
    except Exception as e:
        print(f"❌ Database stats error: {e}")
        return {
            'total_feedback': 0,
            'avg_rating': 0,
            'recent_feedback': []
        }

def view_feedback_admin():
    """Admin function to view all feedback"""
    try:
        conn = sqlite3.connect(DATABASE_FILE)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT id, timestamp, feedback_type, rating, comments, user_email, created_at
            FROM feedback 
            ORDER BY created_at DESC
        ''')
        
        feedback_data = cursor.fetchall()
        conn.close()
        
        if not feedback_data:
            return "No feedback found in database."
        
        # Format feedback data
        result = "# πŸ“Š Feedback Database\n\n"
        result += f"**Total Feedback Entries:** {len(feedback_data)}\n\n"
        
        for entry in feedback_data:
            id_val, timestamp, feedback_type, rating, comments, user_email, created_at = entry
            result += f"## Entry #{id_val}\n"
            result += f"**Date:** {timestamp}\n"
            result += f"**Type:** {feedback_type}\n"
            result += f"**Rating:** {rating}/5 ⭐\n"
            result += f"**Comments:** {comments}\n"
            result += f"**Email:** {user_email if user_email else 'Not provided'}\n"
            result += f"**Created:** {created_at}\n"
            result += "---\n\n"
        
        return result
    except Exception as e:
        return f"❌ Error accessing database: {str(e)}"

# Albert Chatbot Functions
def call_hugging_face_api(prompt):
    """Call Hugging Face API for Albert chatbot"""
    if not HF_TOKEN:
        return None
    
    headers = {
        "Authorization": f"Bearer {HF_TOKEN}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "deepseek-ai/DeepSeek-V3-0324",
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": 200,
        "temperature": 0.7
    }
    
    try:
        response = requests.post(
            "https://router.huggingface.co/v1/chat/completions",
            headers=headers,
            json=data,
            timeout=30
        )
        
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content']
        else:
            print(f"❌ Albert API error: {response.status_code}")
            return None
    except Exception as e:
        print(f"❌ Albert API error: {str(e)}")
        return None

def call_hugging_face_api_content(prompt):
    """Call Hugging Face API for content generation with more tokens"""
    if not HF_TOKEN:
        return None
    
    headers = {
        "Authorization": f"Bearer {HF_TOKEN}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "deepseek-ai/DeepSeek-V3-0324",
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": 1000,  # More tokens for content generation
        "temperature": 0.7
    }
    
    try:
        print(f"🌐 Making API call for content generation...")
        print(f"πŸ”— Endpoint: https://router.huggingface.co/v1/chat/completions")
        print(f"πŸ”‘ Token available: {HF_TOKEN is not None}")
        print(f"πŸ“ Prompt length: {len(prompt)} characters")
        
        response = requests.post(
            "https://router.huggingface.co/v1/chat/completions",
            headers=headers,
            json=data,
            timeout=60  # Longer timeout for content generation
        )
        
        print(f"πŸ“Š Response status: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            content = result['choices'][0]['message']['content']
            print(f"βœ… Content generation successful! Length: {len(content)} characters")
            return content
        else:
            print(f"❌ Content API error: {response.status_code}")
            print(f"❌ Response: {response.text}")
            return None
    except Exception as e:
        print(f"❌ Content API error: {str(e)}")
        return None

def generate_image_with_huggingface(prompt, topic, content_type):
    """Generate image using Hugging Face text-to-image models"""
    try:
        if not HF_TOKEN:
            print("❌ No HF_TOKEN available for image generation")
            return None
            
        # Use Hugging Face Inference API for image generation
        headers = {
            "Authorization": f"Bearer {HF_TOKEN}",
            "Content-Type": "application/json"
        }
        
        # Try different image generation models
        models = [
            "stabilityai/stable-diffusion-xl-base-1.0",
            "runwayml/stable-diffusion-v1-5", 
            "CompVis/stable-diffusion-v1-4"
        ]
        
        for model in models:
            try:
                print(f"🎨 Trying image generation with {model}")
                
                data = {
                    "inputs": prompt,
                    "parameters": {
                        "num_inference_steps": 20,
                        "guidance_scale": 7.5,
                        "width": 512,
                        "height": 512
                    }
                }
                
                response = requests.post(
                    f"https://api-inference.huggingface.co/models/{model}",
                    headers=headers,
                    json=data,
                    timeout=30
                )
                
                if response.status_code == 200:
                    # Convert to base64 data URL
                    import base64
                    image_base64 = base64.b64encode(response.content).decode('utf-8')
                    data_url = f"data:image/png;base64,{image_base64}"
                    
                    print(f"βœ… Generated image with {model}")
                    return data_url
                else:
                    print(f"❌ {model} failed: {response.status_code}")
                    continue
                    
            except Exception as e:
                print(f"❌ {model} error: {str(e)}")
                continue
        
        return None
        
    except Exception as e:
        print(f"❌ Image generation error: {str(e)}")
        return None

def get_educational_image_url(topic, description, content_type):
    """Get educational image URL using Hugging Face generation first, then fallbacks"""
    try:
        # Create a detailed prompt for image generation
        image_prompt = f"Educational illustration of {topic}, {description}, {content_type}, clean diagram, colorful, professional, suitable for middle school students"
        
        print(f"🎨 Generating image with prompt: {image_prompt}")
        
        # Try to generate image with Hugging Face first
        generated_image = generate_image_with_huggingface(image_prompt, topic, content_type)
        
        if generated_image:
            print(f"βœ… Generated image successfully")
            return generated_image
        
        # Fallback to reliable sources if generation fails
        print("πŸ”„ Image generation failed, using fallback sources")
        
        educational_sources = [
            # 1. Lorem Picsum (reliable placeholder)
            f"https://picsum.photos/800/600?random={hash(topic) % 1000}",
            
            # 2. Placeholder with educational styling
            f"https://via.placeholder.com/800x600/667eea/ffffff?text={topic.replace(' ', '+')}+Educational+Content",
            
            # 3. Educational diagram generator
            f"https://via.placeholder.com/800x600/4f46e5/ffffff?text={content_type.replace(' ', '+')}+{topic.replace(' ', '+')}",
        ]
        
        # Try each fallback source
        for i, url in enumerate(educational_sources):
            try:
                print(f"πŸ” Trying fallback source {i+1}: {url}")
                response = requests.head(url, timeout=5)
                if response.status_code == 200:
                    print(f"βœ… Found working fallback image: {url}")
                    return url
            except:
                continue
        
        # Final fallback
        return f"https://via.placeholder.com/800x600/667eea/ffffff?text={topic.replace(' ', '+')}+{content_type.replace(' ', '+')}"
    
    except Exception as e:
        print(f"❌ Image URL generation error: {str(e)}")
        return f"https://via.placeholder.com/800x600/667eea/ffffff?text={topic.replace(' ', '+')}+{content_type.replace(' ', '+')}"

def generate_real_image(description, topic, content_type):
    """Generate actual image for educational content using multiple sources"""
    try:
        # Get image URL from reliable sources
        image_url = get_educational_image_url(topic, description, content_type)
        
        print(f"πŸ–ΌοΈ Using image URL: {image_url}")
        
        # Create simple HTML with just the image - no fallback HTML
        image_html = f"""
<div style="margin: 20px 0; text-align: center;">
    <img src="{image_url}" 
         alt="{description}" 
         style="max-width: 100%; height: auto; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); border: 2px solid #e2e8f0;"
         loading="lazy">
</div>
"""
        return image_html
    
    except Exception as e:
        print(f"❌ Image generation error: {str(e)}")
        # Simple fallback without complex HTML
        return f"""
<div style="margin: 20px 0; text-align: center; padding: 20px; background: #f8f9fa; border-radius: 12px;">
    <div style="font-size: 48px; margin-bottom: 10px;">πŸ–ΌοΈ</div>
    <p style="color: #667eea; font-weight: bold;">{description}</p>
</div>
"""

def generate_image_placeholder(description, topic, content_type):
    """Generate image placeholder with description for educational content (fallback)"""
    # Create a structured image placeholder that can be replaced with real images
    image_placeholder = f"""
<div style="border: 2px dashed #667eea; padding: 20px; margin: 20px 0; text-align: center; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 12px;">
    <div style="font-size: 48px; margin-bottom: 10px;">πŸ–ΌοΈ</div>
    <h3 style="color: #667eea; margin: 10px 0;">πŸ“Έ Image Placeholder</h3>
    <p style="color: #4a5568; margin: 10px 0;"><strong>Description:</strong> {description}</p>
    <p style="color: #718096; font-size: 14px; margin: 5px 0;"><strong>Topic:</strong> {topic}</p>
    <p style="color: #718096; font-size: 14px; margin: 5px 0;"><strong>Content Type:</strong> {content_type}</p>
    <div style="background: #667eea; color: white; padding: 8px 16px; border-radius: 6px; display: inline-block; margin-top: 10px; font-size: 12px;">
        πŸ’‘ This image would enhance the learning experience
    </div>
</div>
"""
    return image_placeholder

def create_content_agent(topic, subject, grade_level, difficulty, content_type, content_length):
    """Enhanced content generation agent with multimedia capabilities"""
    
    # Define image suggestions based on content type and topic
    image_suggestions = {
        "Worksheets": [
            f"Visual diagram showing {topic} concepts",
            f"Step-by-step illustration for {topic} problems",
            f"Interactive chart demonstrating {topic} principles"
        ],
        "Handouts": [
            f"Infographic summarizing {topic} key points",
            f"Visual timeline of {topic} development",
            f"Diagram showing {topic} relationships"
        ],
        "Study Guides": [
            f"Concept map of {topic} topics",
            f"Visual summary of {topic} main ideas",
            f"Flowchart showing {topic} processes"
        ],
        "Activities": [
            f"Step-by-step visual instructions for {topic} activity",
            f"Before and after examples of {topic} work",
            f"Visual checklist for {topic} completion"
        ],
        "Presentations": [
            f"Title slide with {topic} theme",
            f"Key concept visualization for {topic}",
            f"Summary slide with {topic} highlights"
        ],
        "Lesson Materials": [
            f"Opening visual hook for {topic} lesson",
            f"Visual examples of {topic} in real life",
            f"Closing visual summary of {topic} learning"
        ]
    }
    
    # Get image suggestions for this content type
    images = image_suggestions.get(content_type, [f"Educational illustration about {topic}"])
    
    # Define content type specific formatting and structure
    content_type_formats = {
        "Worksheets": {
            "structure": "Interactive worksheet with numbered problems, answer spaces, and self-assessment",
            "formatting": "Use checkboxes, fill-in-the-blank spaces, numbered problems, and answer keys",
            "sections": ["Introduction", "Learning Objectives", "Practice Problems", "Word Problems", "Self-Assessment", "Answer Key"],
            "special_elements": "Include answer spaces, checkboxes for completion, and step-by-step problem solving"
        },
        "Handouts": {
            "structure": "Reference handout with key concepts, formulas, and quick lookup information",
            "formatting": "Use bullet points, highlighted boxes, tables, and clear headings",
            "sections": ["Overview", "Key Concepts", "Important Formulas", "Examples", "Quick Reference", "Additional Resources"],
            "special_elements": "Include summary tables, highlighted key terms, and visual diagrams"
        },
        "Study Guides": {
            "structure": "Comprehensive study guide with summaries, review materials, and practice questions",
            "formatting": "Use numbered lists, checkboxes, summary tables, and review checklists",
            "sections": ["Topic Summary", "Key Points", "Important Concepts", "Practice Questions", "Review Checklist", "Test Tips"],
            "special_elements": "Include memory aids, mnemonics, and test-taking strategies"
        },
        "Activities": {
            "structure": "Hands-on activity with detailed instructions, materials list, and observation sheets",
            "formatting": "Use numbered steps, safety notes, observation tables, and discussion questions",
            "sections": ["Activity Overview", "Materials Needed", "Step-by-Step Instructions", "Observations", "Discussion Questions", "Extensions"],
            "special_elements": "Include safety considerations, data collection sheets, and reflection questions"
        },
        "Presentations": {
            "structure": "Presentation slides with talking points, visual elements, and interactive components",
            "formatting": "Use slide format with bullet points, speaker notes, and visual transitions",
            "sections": ["Title Slide", "Agenda", "Key Points", "Examples", "Summary", "Q&A"],
            "special_elements": "Include speaker notes, interactive polls, and visual cues"
        },
        "Lesson Materials": {
            "structure": "Complete lesson materials for teachers with instructions, activities, and assessments",
            "formatting": "Include teacher tips, timing suggestions, differentiation options, and rubrics",
            "sections": ["Lesson Overview", "Learning Objectives", "Teacher Notes", "Student Activities", "Assessment", "Resources"],
            "special_elements": "Include pacing guides, differentiation strategies, and assessment rubrics"
        }
    }
    
    format_info = content_type_formats.get(content_type, content_type_formats["Worksheets"])
    
    # Define length-specific constraints
    length_constraints = {
        "Short (1-2 pages)": {
            "max_sections": 4,
            "max_words": 800,
            "instruction": "Keep content VERY concise and focused. Maximum 4 sections. Use bullet points and brief explanations. Avoid lengthy examples."
        },
        "Medium (3-5 pages)": {
            "max_sections": 6,
            "max_words": 1500,
            "instruction": "Provide comprehensive coverage with moderate detail. Include 5-6 sections with examples and practice."
        },
        "Long (6+ pages)": {
            "max_sections": 8,
            "max_words": 2500,
            "instruction": "Create extensive content with detailed explanations, multiple examples, and comprehensive practice sections."
        }
    }
    
    length_info = length_constraints.get(content_length, length_constraints["Medium (3-5 pages)"])
    
    # Create enhanced prompt for agent-based generation
    agent_prompt = f"""You are an advanced educational content generation agent. Create comprehensive educational {content_type.lower()} with multimedia integration.

TOPIC: {topic}
SUBJECT: {subject}
GRADE LEVEL: {grade_level}
DIFFICULTY: {difficulty}
CONTENT TYPE: {content_type}
LENGTH: {content_length}

LENGTH CONSTRAINTS (CRITICAL - MUST FOLLOW):
- Target Length: {content_length}
- Maximum Sections: {length_info['max_sections']}
- Maximum Words: {length_info['max_words']}
- Instruction: {length_info['instruction']}

CONTENT TYPE SPECIFIC REQUIREMENTS:
Structure: {format_info['structure']}
Formatting: {format_info['formatting']}
Sections: {', '.join(format_info['sections'])}
Special Elements: {format_info['special_elements']}

AGENT INSTRUCTIONS:
1. Generate rich, engaging educational content specifically formatted for {content_type}
2. STRICTLY follow the length constraints: {length_info['instruction']}
3. Include specific image placeholders with detailed descriptions
4. Create interactive elements and visual aids appropriate for {content_type}
5. Structure content for maximum learning impact using {content_type} best practices
6. Include multimedia integration points
7. Apply {content_type}-specific formatting and layout
8. KEEP CONTENT WITHIN {length_info['max_words']} WORDS MAXIMUM

CONTENT STRUCTURE FOR {content_type.upper()}:
{chr(10).join([f"- {section}" for section in format_info['sections']])}

IMAGE INTEGRATION:
Include these specific image suggestions:
{chr(10).join([f"- {img}" for img in images])}

FORMAT REQUIREMENTS FOR {content_type.upper()}:
- Use markdown formatting appropriate for {content_type}
- Include image placeholders: [IMAGE: description]
- Add interactive elements: [INTERACTIVE: description]
- Include multimedia links: [MEDIA: description]
- Use engaging headers and subheaders
- Include callout boxes and highlights
- Apply {format_info['formatting']}

SPECIAL FORMATTING FOR {content_type.upper()}:
{format_info['special_elements']}

Make the content visually rich, educationally sound, and ready for multimedia integration with {content_type}-specific formatting."""

    return agent_prompt

def process_content_with_images(content, topic, content_type):
    """Process generated content to include real images and multimedia elements"""
    
    # Replace image placeholders with actual images
    import re
    
    # Fix LaTeX math rendering by converting to HTML
    def fix_latex_math(match):
        latex_formula = match.group(1)
        
        # Handle fractions first (most complex) - improved regex
        def process_fraction(match):
            numerator = match.group(1)
            denominator = match.group(2)
            return f'<div style="display: inline-block; text-align: center; vertical-align: middle; margin: 0 5px;"><div style="border-bottom: 1px solid #333; padding-bottom: 2px; font-size: 0.9em;">{numerator}</div><div style="padding-top: 2px; font-size: 0.9em;">{denominator}</div></div>'
        
        # Process fractions: \frac{numerator}{denominator} - more robust regex
        latex_formula = re.sub(r'\\frac\{([^{}]+)\}\{([^{}]+)\}', process_fraction, latex_formula)
        
        # Handle text commands more carefully
        latex_formula = latex_formula.replace('\\text{', '<span style="font-style: normal;">')
        
        # Handle math symbols
        latex_formula = latex_formula.replace('\\times', 'Γ—')
        latex_formula = latex_formula.replace('\\rightarrow', 'β†’')
        latex_formula = latex_formula.replace('\\leftarrow', '←')
        latex_formula = latex_formula.replace('\\leq', '≀')
        latex_formula = latex_formula.replace('\\geq', 'β‰₯')
        latex_formula = latex_formula.replace('\\neq', 'β‰ ')
        latex_formula = latex_formula.replace('\\approx', 'β‰ˆ')
        latex_formula = latex_formula.replace('\\pm', 'Β±')
        latex_formula = latex_formula.replace('\\sqrt{', '√(')
        latex_formula = latex_formula.replace('\\pi', 'Ο€')
        latex_formula = latex_formula.replace('\\alpha', 'Ξ±')
        latex_formula = latex_formula.replace('\\beta', 'Ξ²')
        latex_formula = latex_formula.replace('\\gamma', 'Ξ³')
        latex_formula = latex_formula.replace('\\delta', 'Ξ΄')
        latex_formula = latex_formula.replace('\\theta', 'ΞΈ')
        latex_formula = latex_formula.replace('\\lambda', 'Ξ»')
        latex_formula = latex_formula.replace('\\mu', 'ΞΌ')
        latex_formula = latex_formula.replace('\\sigma', 'Οƒ')
        latex_formula = latex_formula.replace('\\tau', 'Ο„')
        latex_formula = latex_formula.replace('\\phi', 'Ο†')
        latex_formula = latex_formula.replace('\\omega', 'Ο‰')
        
        # Handle superscripts and subscripts
        latex_formula = re.sub(r'\^(\w+)', r'<sup>\1</sup>', latex_formula)
        latex_formula = re.sub(r'_(\w+)', r'<sub>\1</sub>', latex_formula)
        
        # Clean up any remaining unmatched braces
        latex_formula = latex_formula.replace('{', '').replace('}', '')
        
        return f'<div style="text-align: center; margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #667eea; font-family: \'Times New Roman\', serif; font-size: 1.1em;">{latex_formula}</div>'
    
    # Find LaTeX math formulas and convert them (both [formula] and (formula) formats)
    latex_patterns = [
        re.compile(r'\[([^\]]+)\]', re.MULTILINE),  # [formula] format
        re.compile(r'\(([^)]+)\)', re.MULTILINE)    # (formula) format
    ]
    
    for pattern in latex_patterns:
        content = pattern.sub(fix_latex_math, content)
    
    # Find all IMAGE: description patterns (both [IMAGE: description] and IMAGE: description)
    image_patterns = [
        r'\[IMAGE:\s*([^\]]+)\]',  # [IMAGE: description]
        r'IMAGE:\s*([^\n<]+?)(?=\s*<|$|\n)',  # IMAGE: description (standalone, stop at < or end)
    ]
    
    total_images = 0
    for pattern in image_patterns:
        images = re.findall(pattern, content, re.MULTILINE)
        total_images += len(images)
        
        print(f"πŸ–ΌοΈ Found {len(images)} image placeholders with pattern: {pattern}")
        
        # Replace with real images
        for i, image_desc in enumerate(images):
            print(f"πŸ” Processing image: {image_desc.strip()}")
            image_html = generate_real_image(image_desc.strip(), topic, content_type)
            
            # Replace both formats
            content = content.replace(f'[IMAGE: {image_desc}]', image_html)
            content = content.replace(f'IMAGE: {image_desc}', image_html)
    
    print(f"πŸ–ΌοΈ Total images processed: {total_images}")
    
    # Add multimedia enhancement sections
    multimedia_section = f"""
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; margin: 20px 0; border-radius: 12px;">
    <h3 style="color: white; margin: 0 0 15px 0;">🎨 Multimedia Enhancement</h3>
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
        <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
            <h4 style="color: white; margin: 0 0 10px 0;">πŸ“Έ Visual Aids</h4>
            <p style="margin: 0; font-size: 14px;">Interactive diagrams and illustrations to support learning</p>
        </div>
        <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
            <h4 style="color: white; margin: 0 0 10px 0;">πŸŽ₯ Video Content</h4>
            <p style="margin: 0; font-size: 14px;">Educational videos demonstrating key concepts</p>
        </div>
        <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
            <h4 style="color: white; margin: 0 0 10px 0;">πŸ”Š Audio Resources</h4>
            <p style="margin: 0; font-size: 14px;">Audio explanations and pronunciation guides</p>
        </div>
    </div>
</div>
"""
    
    # Insert multimedia section before the end
    if "## Additional Resources" in content:
        content = content.replace("## Additional Resources", multimedia_section + "\n## Additional Resources")
    else:
        content += multimedia_section
    
    return content

def generate_albert_response(user_message, user_name, age_group, chat_history):
    """Generate Albert's response using AI or fallback"""
    
    # Try Hugging Face API first if token is available
    if HF_TOKEN:
        try:
            # Create Albert's personality prompt based on age group
            age_emojis = {
                "K-2": "🌟",
                "3-5": "πŸš€", 
                "6-8": "⚑",
                "9-12": "πŸŽ“",
                "Adult": "πŸ’‘"
            }
            
            age_emoji = age_emojis.get(age_group, "🌟")
            
            # Build context from chat history
            context = ""
            if chat_history and len(chat_history) > 1:
                context = "\n\nPrevious conversation:\n"
                for i, (user_msg, albert_msg) in enumerate(chat_history[-3:]):  # Last 3 exchanges
                    if user_msg and albert_msg:
                        context += f"User: {user_msg}\nAlbert: {albert_msg}\n"
            
            prompt = f"""You are Albert 🧠, a fun and encouraging educational chatbot! 

User Info:
- Name: {user_name}
- Age Group: {age_group} {age_emoji}

Your personality:
- Use lots of emojis and fun expressions! 😊
- Be encouraging and positive
- Explain things in a simple, engaging way
- Ask follow-up questions to keep learning going
- Use age-appropriate language for {age_group}
- Be enthusiastic about learning!
- Remember our conversation and build on previous topics!

{context}
Current question: {user_message}

Respond as Albert with enthusiasm, emojis, and helpful explanations! Keep it concise (2-3 sentences max)."""

            # Call Hugging Face API directly for Albert
            ai_content = call_hugging_face_api(prompt)
            
            if ai_content:
                return ai_content
        except Exception as e:
            print(f"❌ Albert API error: {str(e)}")
    
    # Fallback responses based on common questions
    fallback_responses = {
        "hello": f"Hi {user_name}! 🧠✨ I'm Albert, your learning buddy! What would you like to learn about today? 😊",
        "hi": f"Hey there {user_name}! πŸŽ‰ Ready for some fun learning? Ask me anything! πŸš€",
        "help": f"Of course {user_name}! 🧠 I'm here to help you understand any topic! Just ask me a question and I'll explain it in a fun way! 😊✨",
        "math": f"Math is awesome {user_name}! πŸ”’βœ¨ Let me know what specific math topic you're curious about and I'll make it super fun to understand! 🎯",
        "science": f"Science is fascinating {user_name}! πŸ”¬πŸŒŸ Tell me what science topic you want to explore and I'll explain it with cool examples! πŸš€",
        "english": f"Language is powerful {user_name}! πŸ“šπŸ’« What English topic would you like to learn about? I'll make it engaging and fun! ✨",
        "history": f"History is like a time machine {user_name}! ⏰🎭 What historical period or event interests you? I'll bring it to life! 🌟",
        "art": f"Art is creativity in action {user_name}! 🎨✨ What kind of art or creative topic would you like to explore? Let's get creative! πŸš€"
    }
    
    # Check for keywords in the message
    message_lower = user_message.lower()
    for keyword, response in fallback_responses.items():
        if keyword in message_lower:
            return response
    
    # Default encouraging response
    return f"That's a great question {user_name}! 🧠✨ I'd love to help you understand that! Can you tell me more about what specific part you'd like to learn about? I'm here to make learning fun! πŸ˜ŠπŸš€"

def chat_with_albert(user_message, user_name, age_group, chat_history):
    """Handle the chat conversation with Albert"""
    
    if not user_message.strip():
        return chat_history, ""
    
    # Add user message to history
    if chat_history is None:
        chat_history = []
    
    # Add user message
    chat_history.append([user_message, None])
    
    # Generate Albert's response
    albert_response = generate_albert_response(user_message, user_name, age_group, chat_history)
    
    # Add Albert's response
    chat_history[-1][1] = f"🧠 Albert: {albert_response}"
    
    return chat_history, ""

# Initialize database on startup
init_database()

# Create Gradio interface with custom CSS
with gr.Blocks(
    title="BrightMind AI - Educational Content Generator", 
    theme=gr.themes.Soft(),
    css="""
    /* Modern UI Framework */
    .gradio-container {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        background: #ffffff;
        min-height: 100vh;
        position: relative;
        overflow: hidden;
    }
    
    /* Animated Background */
    .gradio-container::before {
        content: '';
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: 
            radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
            radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.1) 0%, transparent 50%),
            radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.1) 0%, transparent 50%);
        animation: backgroundShift 15s ease-in-out infinite;
        z-index: -1;
        pointer-events: none;
    }
    
    .gradio-container::after {
        content: '';
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: 
            radial-gradient(2px 2px at 20px 30px, #cbd5e0, transparent),
            radial-gradient(2px 2px at 40px 70px, #a0aec0, transparent),
            radial-gradient(1px 1px at 90px 40px, #e2e8f0, transparent),
            radial-gradient(1px 1px at 130px 80px, #cbd5e0, transparent),
            radial-gradient(2px 2px at 160px 30px, #a0aec0, transparent);
        background-repeat: repeat;
        background-size: 200px 100px;
        animation: particleFloat 20s linear infinite;
        z-index: -1;
        pointer-events: none;
        opacity: 0.6;
    }
    
    @keyframes backgroundShift {
        0%, 100% { 
            transform: translateX(0px) translateY(0px) scale(1);
            filter: hue-rotate(0deg);
        }
        25% { 
            transform: translateX(-20px) translateY(-10px) scale(1.02);
            filter: hue-rotate(90deg);
        }
        50% { 
            transform: translateX(10px) translateY(-20px) scale(0.98);
            filter: hue-rotate(180deg);
        }
        75% { 
            transform: translateX(-10px) translateY(10px) scale(1.01);
            filter: hue-rotate(270deg);
        }
    }
    
    @keyframes particleFloat {
        0% { transform: translateY(0px) translateX(0px); }
        25% { transform: translateY(-30px) translateX(10px); }
        50% { transform: translateY(-60px) translateX(-5px); }
        75% { transform: translateY(-30px) translateX(15px); }
        100% { transform: translateY(0px) translateX(0px); }
    }
    
    /* Modern Card System */
    .modern-card {
        background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
        border-radius: 24px;
        padding: 32px;
        margin: 24px 0;
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        backdrop-filter: blur(20px);
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
    }
    
    .modern-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #667eea, #764ba2, #f093fb);
        border-radius: 24px 24px 0 0;
    }
    
    .modern-card:hover {
        transform: translateY(-8px) scale(1.02);
        box-shadow: 0 35px 70px rgba(0, 0, 0, 0.15);
    }
    
    /* Enhanced Input Styling - Force Text Visibility */
    .gradio-container input, 
    .gradio-container textarea, 
    .gradio-container select,
    .gradio-container input[type="text"],
    .gradio-container input[type="email"],
    .gradio-container input[type="password"],
    .gradio-container textarea,
    .gradio-container select {
        border-radius: 16px !important;
        border: 2px solid #e2e8f0 !important;
        padding: 16px 20px !important;
        font-size: 15px !important;
        font-weight: 500 !important;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
        background: #ffffff !important;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05) !important;
        color: #1a202c !important;
    }
    
    .gradio-container input::placeholder, 
    .gradio-container textarea::placeholder {
        color: #718096 !important;
        opacity: 1 !important;
    }
    
    /* Dropdown and Select Styling - Black text on white background */
    .gradio-container select,
    .gradio-container select option,
    .gradio-container .dropdown,
    .gradio-container .dropdown *,
    .gradio-container .dropdown .wrap,
    .gradio-container .dropdown .wrap *,
    .gradio-container .gr-dropdown,
    .gradio-container .gr-dropdown *,
    .gradio-container .gr-dropdown select,
    .gradio-container .gr-dropdown select option {
        color: #000000 !important;
        background: #ffffff !important;
        border: 1px solid #e2e8f0 !important;
    }
    
    /* Force dropdown text visibility with maximum specificity */
    .gradio-container .dropdown span,
    .gradio-container .dropdown div,
    .gradio-container .dropdown p,
    .gradio-container .dropdown li,
    .gradio-container .dropdown a,
    .gradio-container .gr-dropdown span,
    .gradio-container .gr-dropdown div,
    .gradio-container .gr-dropdown p,
    .gradio-container .gr-dropdown li,
    .gradio-container .gr-dropdown a {
        color: #000000 !important;
        background: transparent !important;
    }
    
    /* Dropdown hover states */
    .gradio-container select:hover,
    .gradio-container .dropdown:hover,
    .gradio-container .gr-dropdown:hover {
        background: #f8f9fa !important;
        border: 1px solid #cbd5e0 !important;
    }
    
    /* Dropdown focus states */
    .gradio-container select:focus,
    .gradio-container .dropdown:focus,
    .gradio-container .gr-dropdown:focus {
        background: #ffffff !important;
        border: 1px solid #667eea !important;
        outline: none !important;
    }
    
    /* Dropdown options list */
    .gradio-container .dropdown .options,
    .gradio-container .dropdown .options *,
    .gradio-container .gr-dropdown .options,
    .gradio-container .gr-dropdown .options * {
        color: #000000 !important;
        background: #ffffff !important;
    }
    
    /* Force visibility for dropdown option text */
    .gradio-container .dropdown .option,
    .gradio-container .dropdown .option *,
    .gradio-container .dropdown .item,
    .gradio-container .dropdown .item *,
    .gradio-container .gr-dropdown .option,
    .gradio-container .gr-dropdown .option *,
    .gradio-container .gr-dropdown .item,
    .gradio-container .gr-dropdown .item * {
        color: #000000 !important;
        background: transparent !important;
    }
    
    /* Override any conflicting text colors */
    .gradio-container .dropdown *[style*="color"],
    .gradio-container .gr-dropdown *[style*="color"] {
        color: #000000 !important;
    }
    
    /* Dropdown option hover */
    .gradio-container .dropdown .options li:hover,
    .gradio-container .gr-dropdown .options li:hover {
        background: #f8f9fa !important;
        color: #000000 !important;
    }
    
    /* Additional dropdown selectors for comprehensive coverage */
    .gradio-container [class*="dropdown"],
    .gradio-container [class*="select"],
    .gradio-container [data-testid*="dropdown"],
    .gradio-container [data-testid*="select"] {
        color: #000000 !important;
        background: #ffffff !important;
        border: 1px solid #e2e8f0 !important;
    }
    
    .gradio-container [class*="dropdown"] *,
    .gradio-container [class*="select"] *,
    .gradio-container [data-testid*="dropdown"] *,
    .gradio-container [data-testid*="select"] * {
        color: #000000 !important;
        background: #ffffff !important;
    }
    
    /* Force all form selects to be black on white */
    .gradio-container form select,
    .gradio-container form select option,
    .gradio-container .form select,
    .gradio-container .form select option {
        color: #000000 !important;
        background: #ffffff !important;
        border: 1px solid #e2e8f0 !important;
    }
    
    /* Ultimate dropdown text visibility fix */
    .gradio-container .dropdown,
    .gradio-container .gr-dropdown,
    .gradio-container select {
        color: #000000 !important;
    }
    
    .gradio-container .dropdown *,
    .gradio-container .gr-dropdown *,
    .gradio-container select * {
        color: #000000 !important;
    }
    
    /* Override any white or transparent text that might be invisible */
    .gradio-container .dropdown *[style*="color: white"],
    .gradio-container .dropdown *[style*="color: #fff"],
    .gradio-container .dropdown *[style*="color: #ffffff"],
    .gradio-container .dropdown *[style*="color: transparent"],
    .gradio-container .gr-dropdown *[style*="color: white"],
    .gradio-container .gr-dropdown *[style*="color: #fff"],
    .gradio-container .gr-dropdown *[style*="color: #ffffff"],
    .gradio-container .gr-dropdown *[style*="color: transparent"] {
        color: #000000 !important;
        opacity: 1 !important;
    }
    
    .gradio-container input:focus, 
    .gradio-container textarea:focus, 
    .gradio-container select:focus {
        border-color: #667eea !important;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1), 0 8px 25px rgba(0, 0, 0, 0.1) !important;
        outline: none !important;
        transform: translateY(-2px) !important;
        color: #1a202c !important;
        background: #ffffff !important;
    }
    
    /* Force text visibility in all text elements */
    .gradio-container * {
        color: inherit !important;
    }
    
    .gradio-container input, 
    .gradio-container textarea, 
    .gradio-container select {
        color: #1a202c !important;
    }
    
    /* Markdown and output text visibility */
    .gradio-container .markdown,
    .gradio-container .markdown *,
    .gradio-container .prose,
    .gradio-container .prose * {
        color: #1a202c !important;
    }
    
    /* Chat message text visibility */
    .gradio-container .chatbot .message,
    .gradio-container .chatbot .message * {
        color: #1a202c !important;
    }
    
    /* Override any conflicting styles */
    .gradio-container .gr-textbox,
    .gradio-container .gr-textbox input,
    .gradio-container .gr-textarea,
    .gradio-container .gr-textarea textarea,
    .gradio-container .gr-dropdown,
    .gradio-container .gr-dropdown select {
        color: #1a202c !important;
        background: #ffffff !important;
    }
    
    /* Force visibility for all generated content */
    .gradio-container .gr-markdown,
    .gradio-container .gr-markdown *,
    .gradio-container .gr-html,
    .gradio-container .gr-html *,
    .gradio-container .output,
    .gradio-container .output *,
    .gradio-container .result,
    .gradio-container .result * {
        color: #1a202c !important;
    }
    
    /* Specific styling for lesson plan and quiz outputs */
    .gradio-container .gr-markdown h1,
    .gradio-container .gr-markdown h2,
    .gradio-container .gr-markdown h3,
    .gradio-container .gr-markdown h4,
    .gradio-container .gr-markdown h5,
    .gradio-container .gr-markdown h6 {
        color: #1a202c !important;
    }
    
    .gradio-container .gr-markdown p,
    .gradio-container .gr-markdown li,
    .gradio-container .gr-markdown span,
    .gradio-container .gr-markdown div {
        color: #1a202c !important;
    }
    
    /* Chat output visibility */
    .gradio-container .chatbot .message p,
    .gradio-container .chatbot .message div,
    .gradio-container .chatbot .message span {
        color: #1a202c !important;
    }
    
    /* Dataset/Table text visibility */
    .gradio-container .gr-dataset,
    .gradio-container .gr-dataset *,
    .gradio-container .gr-dataset table,
    .gradio-container .gr-dataset table *,
    .gradio-container .gr-dataset td,
    .gradio-container .gr-dataset th,
    .gradio-container .gr-dataset tr {
        color: #1a202c !important;
        background: #ffffff !important;
    }
    
    /* Table specific visibility fixes */
    .gradio-container table,
    .gradio-container table *,
    .gradio-container table td,
    .gradio-container table th,
    .gradio-container table tr {
        color: #1a202c !important;
        background: #ffffff !important;
    }
    
    /* Examples table visibility */
    .gradio-container .examples,
    .gradio-container .examples *,
    .gradio-container .examples table,
    .gradio-container .examples table *,
    .gradio-container .examples td,
    .gradio-container .examples th {
        color: #1a202c !important;
        background: #ffffff !important;
    }
    
    /* Slider and form control visibility */
    .gradio-container .gr-slider,
    .gradio-container .gr-slider *,
    .gradio-container .gr-checkbox,
    .gradio-container .gr-checkbox *,
    .gradio-container .gr-radio,
    .gradio-container .gr-radio * {
        color: #1a202c !important;
    }
    
    /* Label text visibility */
    .gradio-container label,
    .gradio-container .gr-label,
    .gradio-container .gr-label * {
        color: #1a202c !important;
    }
    
    /* Force all text to be visible */
    .gradio-container div,
    .gradio-container span,
    .gradio-container p,
    .gradio-container td,
    .gradio-container th,
    .gradio-container li {
        color: #1a202c !important;
    }
    
    /* Override any white text that might be invisible */
    .gradio-container *[style*="color: white"],
    .gradio-container *[style*="color: #fff"],
    .gradio-container *[style*="color: #ffffff"] {
        color: #1a202c !important;
    }
    
    /* Ensure all interactive elements have visible text */
    .gradio-container button,
    .gradio-container .btn,
    .gradio-container .gr-button {
        color: #ffffff !important;
    }
    
    /* Table and dataset specific fixes */
    .gradio-container table td,
    .gradio-container table th,
    .gradio-container .dataset table td,
    .gradio-container .dataset table th {
        color: #1a202c !important;
        background: transparent !important;
    }
    
    /* Form element text visibility */
    .gradio-container .form,
    .gradio-container .form *,
    .gradio-container .gr-form,
    .gradio-container .gr-form * {
        color: #1a202c !important;
    }
    
    /* Quiz Generator specific fixes */
    .gradio-container .gr-slider .wrap,
    .gradio-container .gr-slider .wrap *,
    .gradio-container .gr-slider label,
    .gradio-container .gr-slider .label,
    .gradio-container .gr-slider .gr-label {
        color: #1a202c !important;
    }
    
    /* Comprehensive Slider Visibility */
    .gradio-container .gr-slider,
    .gradio-container .gr-slider *,
    .gradio-container [data-testid="slider"],
    .gradio-container [data-testid="slider"] *,
    .gradio-container .slider,
    .gradio-container .slider * {
        background: #ffffff !important;
        border: 1px solid #e2e8f0 !important;
        border-radius: 8px !important;
    }
    
    /* Slider track visibility */
    .gradio-container .gr-slider .track,
    .gradio-container .gr-slider .rail,
    .gradio-container .gr-slider .slider-track,
    .gradio-container [data-testid="slider"] .track,
    .gradio-container [data-testid="slider"] .rail,
    .gradio-container .slider .track,
    .gradio-container .slider .rail {
        background: #e2e8f0 !important;
        border: 2px solid #cbd5e0 !important;
        height: 8px !important;
        border-radius: 4px !important;
    }
    
    /* Slider thumb visibility */
    .gradio-container .gr-slider .thumb,
    .gradio-container .gr-slider .handle,
    .gradio-container .gr-slider .slider-thumb,
    .gradio-container [data-testid="slider"] .thumb,
    .gradio-container [data-testid="slider"] .handle,
    .gradio-container .slider .thumb,
    .gradio-container .slider .handle {
        background: #000000 !important;
        border: 3px solid #000000 !important;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5) !important;
        width: 20px !important;
        height: 20px !important;
        border-radius: 50% !important;
    }
    
    /* Slider value display */
    .gradio-container .gr-slider .value,
    .gradio-container .gr-slider .gr-number,
    .gradio-container .gr-slider input[type="number"],
    .gradio-container [data-testid="slider"] .value,
    .gradio-container [data-testid="slider"] input,
    .gradio-container .slider .value,
    .gradio-container .slider input {
        color: #1a202c !important;
        background: #ffffff !important;
        border: 1px solid #cbd5e0 !important;
    }
    
    /* Force slider visibility with multiple selectors */
    .gradio-container input[type="range"] {
        -webkit-appearance: none !important;
        appearance: none !important;
        background: #e2e8f0 !important;
        border: 2px solid #cbd5e0 !important;
        height: 8px !important;
        border-radius: 4px !important;
        outline: none !important;
    }
    
    .gradio-container input[type="range"]::-webkit-slider-track {
        -webkit-appearance: none !important;
        appearance: none !important;
        background: #e2e8f0 !important;
        border: 2px solid #cbd5e0 !important;
        height: 8px !important;
        border-radius: 4px !important;
    }
    
    .gradio-container input[type="range"]::-webkit-slider-thumb {
        -webkit-appearance: none !important;
        appearance: none !important;
        background: #000000 !important;
        border: 3px solid #000000 !important;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5) !important;
        width: 20px !important;
        height: 20px !important;
        border-radius: 50% !important;
        cursor: pointer !important;
    }
    
    .gradio-container input[type="range"]::-moz-range-track {
        background: #e2e8f0 !important;
        border: 2px solid #cbd5e0 !important;
        height: 8px !important;
        border-radius: 4px !important;
    }
    
    .gradio-container input[type="range"]::-moz-range-thumb {
        background: #000000 !important;
        border: 3px solid #000000 !important;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5) !important;
        width: 20px !important;
        height: 20px !important;
        border-radius: 50% !important;
        cursor: pointer !important;
    }
    
    /* Microsoft Edge and IE */
    .gradio-container input[type="range"]::-ms-track {
        background: #e2e8f0 !important;
        border: 2px solid #cbd5e0 !important;
        height: 8px !important;
        border-radius: 4px !important;
    }
    
    .gradio-container input[type="range"]::-ms-thumb {
        background: #000000 !important;
        border: 3px solid #000000 !important;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5) !important;
        width: 20px !important;
        height: 20px !important;
        border-radius: 50% !important;
        cursor: pointer !important;
    }
    
    /* Number input visibility */
    .gradio-container .gr-number input,
    .gradio-container .gr-number input[type="number"] {
        color: #1a202c !important;
        background: #ffffff !important;
        border: 1px solid #cbd5e0 !important;
    }
    
    /* Checkbox and radio button labels */
    .gradio-container .gr-checkbox label,
    .gradio-container .gr-radio label,
    .gradio-container .gr-checkbox .label,
    .gradio-container .gr-radio .label {
        color: #1a202c !important;
    }
    
    /* Radio button styling - selected state turns black */
    .gradio-container .gr-radio input[type="radio"] {
        appearance: none !important;
        width: 20px !important;
        height: 20px !important;
        border: 2px solid #e2e8f0 !important;
        border-radius: 50% !important;
        background: #ffffff !important;
        cursor: pointer !important;
        position: relative !important;
    }
    
    .gradio-container .gr-radio input[type="radio"]:checked {
        background: #000000 !important;
        border: 2px solid #000000 !important;
    }
    
    .gradio-container .gr-radio input[type="radio"]:checked::after {
        content: '' !important;
        position: absolute !important;
        top: 50% !important;
        left: 50% !important;
        width: 8px !important;
        height: 8px !important;
        background: #ffffff !important;
        border-radius: 50% !important;
        transform: translate(-50%, -50%) !important;
    }
    
    /* Radio button container styling */
    .gradio-container .gr-radio {
        background: #ffffff !important;
        border: 1px solid #e2e8f0 !important;
        border-radius: 12px !important;
        padding: 16px !important;
        margin: 8px !important;
        transition: all 0.3s ease !important;
    }
    
    .gradio-container .gr-radio:hover {
        background: #f8f9fa !important;
        border: 1px solid #cbd5e0 !important;
        transform: translateY(-2px) !important;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
    }
    
    .gradio-container .gr-radio:has(input[type="radio"]:checked) {
        background: #000000 !important;
        border: 1px solid #000000 !important;
        color: #ffffff !important;
    }
    
    .gradio-container .gr-radio:has(input[type="radio"]:checked) label {
        color: #ffffff !important;
    }
    
    /* Force all quiz form elements to have visible text */
    .gradio-container .quiz-form,
    .gradio-container .quiz-form *,
    .gradio-container .quiz-form label,
    .gradio-container .quiz-form .label,
    .gradio-container .quiz-form .gr-label {
        color: #1a202c !important;
    }
    
    /* Override any transparent or invisible text */
    .gradio-container *[style*="opacity: 0"],
    .gradio-container *[style*="opacity:0"],
    .gradio-container .invisible,
    .gradio-container .hidden {
        opacity: 1 !important;
        color: #1a202c !important;
    }
    
    /* Ensure all text in cards is visible */
    .gradio-container .modern-card * {
        color: #1a202c !important;
    }
    
    /* Specific fixes for quiz tab elements */
    .gradio-container .tab-nav .tab-nav button[data-testid="tab-2"] ~ * .gr-slider,
    .gradio-container .tab-nav .tab-nav button[data-testid="tab-2"] ~ * .gr-number,
    .gradio-container .tab-nav .tab-nav button[data-testid="tab-2"] ~ * .gr-checkbox,
    .gradio-container .tab-nav .tab-nav button[data-testid="tab-2"] ~ * .gr-radio {
        color: #1a202c !important;
    }
    
    /* Force white background for all chat elements */
    .gradio-container .gr-chatbot,
    .gradio-container .gr-chatbot *,
    .gradio-container .chatbot,
    .gradio-container .chatbot *,
    .gradio-container [data-testid="chatbot"],
    .gradio-container [data-testid="chatbot"] * {
        background: #ffffff !important;
    }
    
    /* Override any dark themes that might be applied */
    .gradio-container .dark,
    .gradio-container .dark *,
    .gradio-container [data-theme="dark"],
    .gradio-container [data-theme="dark"] * {
        background: #ffffff !important;
        color: #1a202c !important;
    }
    
    /* Force visibility for all text elements */
    .gradio-container * {
        color: #1a202c !important;
    }
    
    /* Override any white or transparent text */
    .gradio-container *[style*="color: white"],
    .gradio-container *[style*="color: #fff"],
    .gradio-container *[style*="color: #ffffff"],
    .gradio-container *[style*="color: transparent"],
    .gradio-container *[style*="opacity: 0"] {
        color: #1a202c !important;
        opacity: 1 !important;
    }
    
    /* Ensure all interactive elements are visible */
    .gradio-container .gr-component,
    .gradio-container .gr-component * {
        color: #1a202c !important;
        background: #ffffff !important;
    }
    
    /* Specific fixes for lesson plan examples */
    .gradio-container .lesson-examples,
    .gradio-container .lesson-examples *,
    .gradio-container .lesson-examples table,
    .gradio-container .lesson-examples table * {
        color: #1a202c !important;
        background: #ffffff !important;
    }
    
    /* Additional slider targeting for all possible selectors */
    .gradio-container .wrap .gr-slider,
    .gradio-container .wrap .gr-slider *,
    .gradio-container .form .gr-slider,
    .gradio-container .form .gr-slider *,
    .gradio-container .block .gr-slider,
    .gradio-container .block .gr-slider *,
    .gradio-container .component .gr-slider,
    .gradio-container .component .gr-slider * {
        background: #ffffff !important;
        border: 1px solid #e2e8f0 !important;
    }
    
    /* Target slider elements by their actual HTML structure */
    .gradio-container .gr-slider .wrap,
    .gradio-container .gr-slider .wrap *,
    .gradio-container .gr-slider .container,
    .gradio-container .gr-slider .container * {
        background: #e2e8f0 !important;
        border: 2px solid #cbd5e0 !important;
    }
    
    /* Force visibility for any slider-like elements */
    .gradio-container [class*="slider"],
    .gradio-container [class*="range"],
    .gradio-container [class*="track"] {
        background: #e2e8f0 !important;
        border: 2px solid #cbd5e0 !important;
    }
    
    .gradio-container [class*="thumb"],
    .gradio-container [class*="handle"] {
        background: #000000 !important;
        border: 3px solid #000000 !important;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5) !important;
    }
    
    /* Premium Button Design */
    .gradio-container .btn {
        border-radius: 16px !important;
        padding: 16px 32px !important;
        font-weight: 700 !important;
        font-size: 15px !important;
        text-transform: uppercase !important;
        letter-spacing: 0.5px !important;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1) !important;
        border: none !important;
        position: relative !important;
        overflow: hidden !important;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
        color: white !important;
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3) !important;
    }
    
    .gradio-container .btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        transition: left 0.6s;
    }
    
    .gradio-container .btn:hover::before {
        left: 100%;
    }
    
    .gradio-container .btn:hover {
        transform: translateY(-4px) scale(1.05) !important;
        box-shadow: 0 15px 35px rgba(102, 126, 234, 0.4) !important;
    }
    
    .gradio-container .btn:active {
        transform: translateY(-2px) scale(1.02) !important;
    }
    
    /* Modern Tab Navigation */
    .gradio-container .tab-nav {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
        border-radius: 20px !important;
        padding: 12px !important;
        margin-bottom: 32px !important;
        box-shadow: 0 15px 35px rgba(102, 126, 234, 0.3) !important;
        backdrop-filter: blur(20px) !important;
    }
    
    
    .gradio-container .tab-nav button {
        border-radius: 16px !important;
        padding: 16px 24px !important;
        font-weight: 700 !important;
        font-size: 15px !important;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1) !important;
        border: none !important;
        background: transparent !important;
        color: rgba(255, 255, 255, 0.8) !important;
        position: relative !important;
        overflow: hidden !important;
    }
    
    .gradio-container .tab-nav button::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    .gradio-container .tab-nav button:hover::before {
        opacity: 1;
    }
    
    .gradio-container .tab-nav button.selected {
        background: rgba(255, 255, 255, 0.2) !important;
        color: white !important;
        backdrop-filter: blur(20px) !important;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1) !important;
    }
    
    .gradio-container .tab-nav button:hover {
        color: white !important;
        transform: translateY(-2px) !important;
    }
    
    /* Enhanced Chat Interface */
    .gradio-container .chatbot {
        border-radius: 24px !important;
        border: 2px solid #e2e8f0 !important;
        background: #ffffff !important;
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1) !important;
        backdrop-filter: blur(20px) !important;
        overflow: hidden !important;
    }
    
    .gradio-container .chatbot .message {
        border-radius: 20px !important;
        margin: 16px 0 !important;
        padding: 20px 24px !important;
        background: #ffffff !important;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08) !important;
        transition: all 0.3s ease !important;
    }
    
    .gradio-container .chatbot .message:hover {
        transform: translateX(4px) !important;
        box-shadow: 0 12px 30px rgba(0, 0, 0, 0.12) !important;
    }
    
    /* Modern Progress System */
    .progress-container {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 24px;
        padding: 40px;
        margin: 32px 0;
        color: white;
        text-align: center;
        box-shadow: 0 25px 50px rgba(102, 126, 234, 0.3);
        backdrop-filter: blur(20px);
        position: relative;
        overflow: hidden;
    }
    
    .progress-container::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
        animation: rotate 20s linear infinite;
    }
    
    @keyframes rotate {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .progress-bar {
        width: 100%;
        height: 16px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        overflow: hidden;
        margin: 24px 0;
        position: relative;
    }
    
    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
        border-radius: 8px;
        animation: progress-animation 2s ease-in-out;
        position: relative;
    }
    
    .progress-fill::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        animation: shimmer 2s infinite;
    }
    
    @keyframes shimmer {
        0% { transform: translateX(-100%); }
        100% { transform: translateX(100%); }
    }
    
    @keyframes progress-animation {
        0% { width: 0%; }
        100% { width: 100%; }
    }
    
    .status-text {
        font-size: 20px;
        font-weight: 700;
        margin: 20px 0;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }
    
    .step-text {
        font-size: 18px;
        opacity: 0.9;
        margin: 12px 0;
        font-weight: 500;
    }
    
    /* Modern Header Design */
    .modern-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 24px;
        padding: 50px;
        margin: 32px 0;
        text-align: center;
        color: white;
        box-shadow: 0 25px 50px rgba(102, 126, 234, 0.3);
        position: relative;
        overflow: hidden;
    }
    
    .modern-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
        animation: float 6s ease-in-out infinite;
    }
    
    @keyframes float {
        0%, 100% { transform: translateY(0px) rotate(0deg); }
        50% { transform: translateY(-20px) rotate(180deg); }
    }
    
    .modern-header h1 {
        font-size: 3rem;
        font-weight: 800;
        margin: 0 0 16px 0;
        text-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        position: relative;
        z-index: 1;
    }
    
    .modern-header p {
        font-size: 1.4rem;
        opacity: 0.9;
        margin: 0;
        position: relative;
        z-index: 1;
        font-weight: 500;
    }
    
    /* Animation Classes */
    .fade-in {
        animation: fadeIn 0.8s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(30px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .slide-in-left {
        animation: slideInLeft 1s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    @keyframes slideInLeft {
        from { transform: translateX(-100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    .slide-in-right {
        animation: slideInRight 1s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    .bounce-in {
        animation: bounceIn 1.2s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    }
    
    @keyframes bounceIn {
        0% { transform: scale(0.3); opacity: 0; }
        50% { transform: scale(1.05); }
        70% { transform: scale(0.9); }
        100% { transform: scale(1); opacity: 1; }
    }
    
    /* Legacy Progress Container */
    .progress-container {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 15px;
        padding: 20px;
        margin: 20px 0;
        box-shadow: 0 8px 32px rgba(0,0,0,0.1);
    }
    .progress-bar {
        width: 100%;
        height: 8px;
        background: rgba(255,255,255,0.2);
        border-radius: 4px;
        overflow: hidden;
        margin: 10px 0;
    }
    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
        border-radius: 4px;
        animation: progress-animation 2s ease-in-out infinite;
    }
    @keyframes progress-animation {
        0% { width: 0%; }
        50% { width: 70%; }
        100% { width: 100%; }
    }
    .typewriter-container {
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        border-radius: 15px;
        padding: 25px;
        margin: 20px 0;
        box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        border-left: 5px solid #667eea;
    }
    .typewriter-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }
    .book-icon {
        font-size: 24px;
        margin-right: 10px;
        color: #8b4513;
        animation: book-flip 2s ease-in-out infinite;
    }
    @keyframes book-flip {
        0%, 100% { transform: rotateY(0deg); }
        50% { transform: rotateY(10deg); }
    }
    .typewriter-text {
        font-family: 'Courier New', monospace;
        font-size: 16px;
        line-height: 1.6;
        color: #2c3e50;
        white-space: pre-wrap;
        min-height: 200px;
    }
    .cursor {
        display: inline-block;
        width: 2px;
        height: 20px;
        background: #667eea;
        animation: blink 1s infinite;
    }
    @keyframes blink {
        0%, 50% { opacity: 1; }
        51%, 100% { opacity: 0; }
    }
    .generation-status {
        text-align: center;
        color: #667eea;
        font-weight: 600;
        margin: 10px 0;
    }
    .professional-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 30px;
        border-radius: 15px;
        text-align: center;
        margin-bottom: 30px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.1);
    }
    .professional-header h1 {
        margin: 0;
        font-size: 2.5em;
        font-weight: 700;
    }
    .professional-header p {
        margin: 10px 0 0 0;
        font-size: 1.2em;
        opacity: 0.9;
    }
    
    /* Albert Chat Avatar Styling */
    .chatbot .message {
        margin: 15px 0;
        padding: 10px;
        border-radius: 10px;
        background: rgba(255,255,255,0.1);
    }
    
    .chatbot .message .avatar {
        width: 300px !important;
        height: 300px !important;
        border-radius: 50% !important;
        margin-right: 20px !important;
        border: 6px solid #667eea !important;
        box-shadow: 0 8px 16px rgba(0,0,0,0.3) !important;
        transition: all 0.3s ease !important;
    }
    
    .chatbot .message .avatar:hover {
        transform: scale(1.1) !important;
        box-shadow: 0 8px 16px rgba(102, 126, 234, 0.4) !important;
    }
    
    .chatbot .message .message-content {
        font-size: 16px;
        line-height: 1.6;
    }
    
    .chatbot .message .message-content strong {
        color: #667eea;
        font-size: 18px;
    }
    
    /* Voice button styling */
    .voice-controls {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-radius: 10px;
        padding: 15px;
        margin: 10px 0;
        border-left: 4px solid #4CAF50;
    }
    
    .voice-controls button {
        background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%) !important;
        color: white !important;
        border: none !important;
        padding: 6px 12px !important;
        border-radius: 6px !important;
        cursor: pointer !important;
        font-weight: 500 !important;
        font-size: 11px !important;
        box-shadow: 0 2px 6px rgba(76, 175, 80, 0.3) !important;
        transition: all 0.3s ease !important;
    }
    
    .voice-controls button:hover {
        transform: translateY(-2px) !important;
        box-shadow: 0 6px 16px rgba(76, 175, 80, 0.4) !important;
    }
    
    /* Auto-scroll for chat */
    #albert_chat .chatbot {
        scroll-behavior: smooth !important;
    }
    
    #albert_chat .overflow-y-auto {
        scroll-behavior: smooth !important;
    }
    </style>
    <script>
    function speakText(text) {
        if ('speechSynthesis' in window) {
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.rate = 0.9;
            utterance.pitch = 1.1;
            utterance.volume = 0.8;
            speechSynthesis.speak(utterance);
        } else {
            alert('Speech synthesis not supported in this browser');
        }
    }
    
    function scrollChatToBottom() {
        // Try multiple selectors to find the chat container
        const selectors = [
            '#albert_chat .chatbot',
            '#albert_chat .overflow-y-auto',
            '#albert_chat .h-full',
            '.chatbot .overflow-y-auto',
            '.chatbot .h-full'
        ];
        
        for (const selector of selectors) {
            const chatContainer = document.querySelector(selector);
            if (chatContainer) {
                chatContainer.scrollTop = chatContainer.scrollHeight;
                return;
            }
        }
        
        // Fallback: scroll the entire page to bottom
        window.scrollTo(0, document.body.scrollHeight);
    }
    
    // Auto-scroll when page loads
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(scrollChatToBottom, 500);
    });
    
    // Auto-scroll when chat updates using MutationObserver
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList' && mutation.target.classList.contains('chatbot')) {
                setTimeout(scrollChatToBottom, 100);
            }
        });
    });
    
    // Start observing when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        const chatElement = document.querySelector('#albert_chat');
        if (chatElement) {
            observer.observe(chatElement, { childList: true, subtree: true });
        }
    });
    
    // Also try to scroll after any Gradio update
    window.addEventListener('load', function() {
        setInterval(scrollChatToBottom, 500);
    });
    
    // More aggressive auto-scroll for chat updates
    function aggressiveScroll() {
        const chatElement = document.querySelector('#albert_chat');
        if (chatElement) {
            // Look for any scrollable container within the chat
            const scrollableElements = chatElement.querySelectorAll('*');
            scrollableElements.forEach(el => {
                if (el.scrollHeight > el.clientHeight) {
                    el.scrollTop = el.scrollHeight;
                }
            });
        }
    }
    
    // Run aggressive scroll more frequently
    setInterval(aggressiveScroll, 200);
    </script>
    """
) as demo:
    
    # Modern Header
    with gr.Row():
        gr.HTML("""
        <div class="modern-header fade-in">
            <h1>🧠 BrightMind AI</h1>
            <p>Professional Educational Content Generator for Teachers</p>
        </div>
        """)
    
    with gr.Tabs():
        with gr.TabItem("🧠 Ask Albert"):
            with gr.Row():
                with gr.Column(scale=1):
                    gr.HTML("""
                    <div class="modern-card slide-in-left">
                        <h2 style="color: #667eea; margin-bottom: 16px; font-size: 1.8rem;">🧠 Meet Albert!</h2>
                        <p style="color: #4a5568; font-size: 1.1rem; margin-bottom: 20px;">Your friendly learning buddy! 😊</p>
                        <div style="background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%); padding: 20px; border-radius: 16px; border-left: 4px solid #667eea;">
                            <p style="margin: 0; color: #2d3748; font-weight: 600;">✨ Tell Albert your name & age β†’ Ask any question β†’ Get fun explanations!</p>
                        </div>
                    </div>
                    """)
                    
                    # Modern Form Section
                    gr.HTML("""
                    <div class="modern-card slide-in-left">
                        <h3 style="color: #667eea; margin-bottom: 20px; font-size: 1.4rem;">πŸ‘€ User Setup</h3>
                    """)
                    
                    user_name = gr.Textbox(
                        label="πŸ‘‹ What's your name?",
                        placeholder="Enter your name here...",
                        value=""
                    )
                    
                    user_age_group = gr.Dropdown(
                        choices=["K-2", "3-5", "6-8", "9-12", "Adult"],
                        label="πŸŽ‚ What's your age group?",
                        value="6-8"
                    )
                    
                    gr.HTML("</div>")
                    
                    # Modern Chat Interface
                    gr.HTML("""
                    <div class="modern-card slide-in-left">
                        <h3 style="color: #667eea; margin-bottom: 20px; font-size: 1.4rem;">πŸ’¬ Chat Interface</h3>
                    """)
                    
                    chat_input = gr.Textbox(
                        label="Ask Albert anything!",
                        placeholder="Type your question here...",
                        lines=2
                    )
                    
                    with gr.Row():
                        send_btn = gr.Button("πŸš€ Send Message", variant="primary")
                        clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
                    
                    gr.HTML("</div>")
                    
                
                with gr.Column(scale=2):
                    # Modern Albert Section
                    gr.HTML("""
                    <div class="modern-card slide-in-right bounce-in">
                        <div style="text-align: center; padding: 20px;">
                            <div style="font-size: 100px; margin-bottom: 20px; filter: drop-shadow(0 10px 20px rgba(0,0,0,0.2));">πŸ‘¨β€πŸ«</div>
                            <h3 style="color: #667eea; margin: 0; font-size: 1.5rem;">Albert is ready to help!</h3>
                        </div>
                    </div>
                    """)
                    
                    # Modern Chat Display
                    gr.HTML("""
                    <div class="modern-card slide-in-right">
                        <h3 style="color: #667eea; margin-bottom: 20px; font-size: 1.4rem;">πŸ’¬ Albert's Chat</h3>
                    """)
                    
                    chat_display = gr.Chatbot(
                        label="",
                        height=400,
                        show_label=False,
                        container=True,
                        bubble_full_width=False,
                        avatar_images=[
                            "https://img.icons8.com/color/48/000000/user-male-circle.png",  # User avatar
                            "https://img.icons8.com/color/48/000000/teacher.png"   # Albert avatar (professional teacher)
                        ],
                        elem_id="albert_chat"
                    )
                    
                    gr.HTML("</div>")
                    
                    # Typing indicator
                    typing_indicator = gr.HTML(
                        value="",
                        visible=False
                    )
                    
                    # Context display
                    context_display = gr.HTML(
                        value=""
                    )
            
            # Event handlers for Albert chat
            def send_message_with_typing(message, name, age_group, history):
                """Send message with typing effect and context memory"""
                if not message.strip():
                    return history, "", "", ""
                
                # Add user message to history
                if history is None:
                    history = []
                
                # Add user message with name
                history.append([f"{name}: {message}", None])
                
                # Show typing indicator with Albert thinking animation
                typing_html = """
                <div style="display: flex; align-items: center; padding: 10px; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 10px; margin: 10px 0;">
                    <div style="width: 40px; height: 40px; background: #8B4513; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 10px; font-size: 20px;">
                        🧠
                    </div>
                    <div style="display: flex; align-items: center;">
                        <span style="font-weight: bold; color: #8B4513; margin-right: 10px;">Albert is thinking</span>
                        <div class="typing-dots">
                            <span>.</span><span>.</span><span>.</span>
                        </div>
                    </div>
                </div>
                <style>
                .typing-dots span {
                    animation: typing 1.4s infinite;
                    margin: 0 2px;
                }
                .typing-dots span:nth-child(2) { animation-delay: 0.2s; }
                .typing-dots span:nth-child(3) { animation-delay: 0.4s; }
                @keyframes typing {
                    0%, 60%, 100% { opacity: 0; }
                    30% { opacity: 1; }
                }
                </style>
                """
                
                # Generate Albert's response with full context
                albert_response = generate_albert_response(message, name, age_group, history)
                
                # Add Albert's response with fast typing effect
                import time
                typed_response = ""
                for i, char in enumerate(albert_response):
                    typed_response += char
                    history[-1][1] = f"{typed_response}|"
                    time.sleep(0.015)  # Even faster typing speed
                
                # Final response without cursor
                history[-1][1] = f"{albert_response}"
                
                # No context memory display
                context_html = ""
                
                # Add auto-scroll trigger
                scroll_script = """
                <script>
                function forceScrollToBottom() {
                    // Try multiple selectors and methods
                    const selectors = [
                        '#albert_chat .chatbot',
                        '#albert_chat .overflow-y-auto', 
                        '#albert_chat .h-full',
                        '.chatbot .overflow-y-auto',
                        '.chatbot .h-full',
                        '[data-testid="chatbot"]',
                        '.gradio-chatbot'
                    ];
                    
                    let scrolled = false;
                    for (const selector of selectors) {
                        const element = document.querySelector(selector);
                        if (element) {
                            element.scrollTop = element.scrollHeight;
                            scrolled = true;
                            break;
                        }
                    }
                    
                    // If no chat container found, scroll the whole page
                    if (!scrolled) {
                        window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
                    }
                }
                
                // Try scrolling multiple times to ensure it works
                setTimeout(forceScrollToBottom, 50);
                setTimeout(forceScrollToBottom, 200);
                setTimeout(forceScrollToBottom, 500);
                setTimeout(forceScrollToBottom, 1000);
                </script>
                """
                
                return history, "", context_html, scroll_script
            
            def clear_chat():
                return [], "", "", ""
            
            def initialize_chat(name, age_group):
                if not name.strip():
                    return [], "", ""
                
                welcome_message = f"Hi {name}! 🧠✨ I'm Albert, your learning buddy! I'm so excited to help you learn! I'll remember our conversation so you can ask follow-up questions anytime. What would you like to know about today? πŸ˜ŠπŸš€"
                return [[None, f"{welcome_message}"]], "", ""
            
            # Connect event handlers
            send_btn.click(
                fn=send_message_with_typing,
                inputs=[chat_input, user_name, user_age_group, chat_display],
                outputs=[chat_display, chat_input, context_display, typing_indicator]
            )
            
            clear_btn.click(
                fn=clear_chat,
                outputs=[chat_display, context_display, context_display, typing_indicator]
            )
            
            # Initialize chat when name is entered
            user_name.change(
                fn=initialize_chat,
                inputs=[user_name, user_age_group],
                outputs=[chat_display, context_display, context_display]
            )
        
        with gr.TabItem("πŸ“š Lesson Plan Generator"):
            with gr.Row():
                with gr.Column():
                    # Modern Form Section
                    gr.HTML("""
                    <div class="modern-card slide-in-left">
                        <h2 style="color: #667eea; margin-bottom: 20px; font-size: 1.8rem;">πŸ“š Lesson Plan Generator</h2>
                        <p style="color: #4a5568; font-size: 1.1rem; margin-bottom: 20px;">Create comprehensive lesson plans with AI assistance</p>
                    """)
                    
                    topic = gr.Textbox(label="πŸ“ Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
                    subject = gr.Dropdown(
                        choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
                        label="πŸ“š Subject",
                        value="Science",
                        interactive=True
                    )
                    grade_level = gr.Dropdown(
                        choices=["K-2", "3-5", "6-8", "9-12"],
                        label="πŸŽ“ Grade Level",
                        value="6-8",
                        interactive=True
                    )
                    duration = gr.Slider(
                        minimum=30,
                        maximum=180,
                        step=15,
                        value=60,
                        label="⏱️ Duration (minutes)"
                    )
                    difficulty = gr.Dropdown(
                        choices=["Beginner", "Intermediate", "Advanced"],
                        label="🎯 Difficulty",
                        value="Intermediate",
                        interactive=True
                    )
                    
                    generate_lesson_btn = gr.Button("πŸš€ Generate Lesson Plan", variant="primary")
                    
                    gr.HTML("</div>")
                
                with gr.Column():
                    # Modern Output Section
                    gr.HTML("""
                    <div class="modern-card slide-in-right">
                        <h3 style="color: #667eea; margin-bottom: 20px; font-size: 1.4rem;">πŸ“‹ Generated Lesson Plan</h3>
                    """)
                    
                    progress_display = gr.HTML("", visible=False)
                    lesson_plan_output = gr.Markdown(label="")
                    
                    gr.HTML("</div>")
                    
                    # Modern Examples Section
                    gr.HTML("""
                    <div class="modern-card slide-in-right">
                        <h3 style="color: #667eea; margin-bottom: 20px; font-size: 1.4rem;">πŸ’‘ Example Topics</h3>
                        <p style="color: #4a5568; margin-bottom: 15px;">Click on any example to get started quickly!</p>
                    """)
                    
                    gr.Dataset(
                        components=[topic, subject, grade_level, duration, difficulty],
                        samples=[
                            ["Photosynthesis", "Science", "6-8", 60, "Intermediate"],
                            ["World War II", "History", "9-12", 90, "Advanced"],
                            ["Basic Algebra", "Mathematics", "3-5", 45, "Beginner"]
                        ],
                    )
                    
                    gr.HTML("</div>")
            
            # Event handler for lesson plan generation
            generate_lesson_btn.click(
                fn=generate_lesson_plan_with_progress,
                inputs=[topic, subject, grade_level, duration, difficulty],
                outputs=[progress_display, lesson_plan_output],
                show_progress=True
            )
            
        
        with gr.TabItem("πŸ“ Content Generator"):
            with gr.Row():
                with gr.Column(scale=1):
                    # Modern Form Section
                    gr.HTML("""
                    <div class="modern-card slide-in-left">
                        <h3>πŸ“ Content Generation</h3>
                        <p>Generate educational materials tailored to your specific needs</p>
                    </div>
                    """)
                    
                    with gr.Group():
                        content_topic = gr.Textbox(label="πŸ“ Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
                        content_subject = gr.Dropdown(
                            choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
                            label="πŸ“š Subject",
                            value="Science",
                            interactive=True
                        )
                        content_grade_level = gr.Dropdown(
                            choices=["K-2", "3-5", "6-8", "9-12"],
                            label="πŸŽ“ Grade Level",
                            value="6-8",
                            interactive=True
                        )
                        content_difficulty = gr.Dropdown(
                            choices=["Beginner", "Intermediate", "Advanced"],
                            label="🎯 Difficulty",
                            value="Intermediate",
                            interactive=True
                        )
                        content_type = gr.Dropdown(
                            choices=["Worksheets", "Handouts", "Study Guides", "Activities", "Presentations", "Lesson Materials"],
                            label="πŸ“„ Content Type",
                            value="Worksheets",
                            interactive=True
                        )
                        content_length = gr.Dropdown(
                            choices=["Short (1-2 pages)", "Medium (3-5 pages)", "Long (6+ pages)"],
                            label="πŸ“ Length",
                            value="Medium (3-5 pages)",
                            interactive=True
                        )
                        
                        generate_content_btn = gr.Button("πŸš€ Generate Content", variant="primary", size="lg")
                        clear_content_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
                
                with gr.Column(scale=2):
                    # Modern Output Section
                    gr.HTML("""
                    <div class="modern-card slide-in-right">
                        <h3>πŸ“„ Generated Content</h3>
                        <p>Your educational materials will appear here</p>
                    </div>
                    """)
                    
                    content_progress_display = gr.HTML("", visible=False)
                    content_output = gr.Markdown(value="Your educational content will appear here...")
                    
                    # Content examples
                    content_examples = gr.Dataset(
                        components=[content_topic, content_subject, content_grade_level, content_difficulty, content_type, content_length],
                        samples=[
                            ["Photosynthesis", "Science", "6-8", "Intermediate", "Worksheets", "Medium (3-5 pages)"],
                            ["World War II", "History", "9-12", "Advanced", "Study Guides", "Long (6+ pages)"],
                            ["Basic Algebra", "Mathematics", "3-5", "Beginner", "Activities", "Short (1-2 pages)"]
                        ],
                        label="πŸ’‘ Content Examples"
                    )
            
            # Event handlers for content generation
            generate_content_btn.click(
                fn=generate_content_with_progress,
                inputs=[content_topic, content_subject, content_grade_level, content_difficulty, content_type, content_length],
                outputs=[content_progress_display, content_output],
                show_progress=True
            )
            
            clear_content_btn.click(
                fn=lambda: ("", "Your educational content will appear here..."),
                inputs=[],
                outputs=[content_progress_display, content_output]
            )

        with gr.TabItem("🎯 Quiz Generator"):
            with gr.Row():
                with gr.Column():
                    # Modern Form Section
                    gr.HTML("""
                    <div class="modern-card slide-in-left">
                        <h2 style="color: #667eea; margin-bottom: 20px; font-size: 1.8rem;">🎯 Quiz Generator</h2>
                        <p style="color: #4a5568; font-size: 1.1rem; margin-bottom: 20px;">Create engaging quizzes with multiple question types</p>
                    """)
                    
                    quiz_topic = gr.Textbox(label="πŸ“ Quiz Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
                    quiz_subject = gr.Dropdown(
                        choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
                        label="πŸ“š Subject",
                        value="Science",
                        interactive=True
                    )
                    quiz_grade_level = gr.Dropdown(
                        choices=["K-2", "3-5", "6-8", "9-12"],
                        label="πŸŽ“ Grade Level",
                        value="6-8",
                        interactive=True
                    )
                    question_count = gr.Slider(
                        minimum=3,
                        maximum=20,
                        step=1,
                        value=5,
                        label="❓ Number of Questions"
                    )
                    question_types = gr.CheckboxGroup(
                        choices=["Multiple Choice", "True/False", "Short Answer", "Fill in the Blank"],
                        label="πŸ“‹ Question Types",
                        value=["Multiple Choice", "True/False"]
                    )
                    
                    generate_quiz_btn = gr.Button("πŸš€ Generate Quiz", variant="primary")
                    
                    gr.HTML("</div>")
                
                with gr.Column():
                    # Modern Output Section
                    gr.HTML("""
                    <div class="modern-card slide-in-right">
                        <h3 style="color: #667eea; margin-bottom: 20px; font-size: 1.4rem;">πŸ“‹ Generated Quiz</h3>
                    """)
                    
                    quiz_progress_display = gr.HTML(visible=False)
                    quiz_output = gr.Markdown(label="")
                    
                    gr.HTML("</div>")
            
            # Event handlers
            generate_quiz_btn.click(
                fn=generate_quiz_with_progress,
                inputs=[quiz_topic, quiz_subject, quiz_grade_level, question_count, question_types],
                outputs=[quiz_progress_display, quiz_output],
                show_progress=True
            )
            
            # Examples
            gr.Examples(
                examples=[
                    ["Photosynthesis", "Science", "6-8", 5, ["Multiple Choice", "True/False"]],
                    ["World War II", "History", "9-12", 8, ["Multiple Choice", "Short Answer"]],
                    ["Basic Algebra", "Mathematics", "3-5", 4, ["Multiple Choice", "Fill in the Blank"]]
                ],
                inputs=[quiz_topic, quiz_subject, quiz_grade_level, question_count, question_types]
            )
        
        
        with gr.TabItem("πŸ”§ Admin Dashboard", visible=False):  # Hidden by default
            with gr.Row():
                with gr.Column():
                    gr.Markdown("""
                    ## πŸ”§ Admin Dashboard
                    
                    **Access Level**: Administrator Only  
                    **Database**: SQLite (feedback.db)  
                    **Last Updated**: Real-time
                    """)
                    
                    refresh_btn = gr.Button("πŸ”„ Refresh Data", variant="secondary")
                    view_feedback_btn = gr.Button("πŸ“Š View All Feedback", variant="primary")
                    
                with gr.Column():
                    admin_output = gr.Markdown(label="Admin Data")
            
            # Event handlers for admin
            def format_stats():
                stats = get_feedback_stats()
                result = f"""
# πŸ“Š Feedback Statistics

**Total Feedback Entries:** {stats['total_feedback']}  
**Average Rating:** {stats['avg_rating']}/5 ⭐  
**Database Status:** βœ… Active

## Recent Feedback (Last 5)
"""
                for entry in stats['recent_feedback']:
                    timestamp, feedback_type, rating, comments, user_email = entry
                    result += f"""
### Entry from {timestamp}
- **Type:** {feedback_type}
- **Rating:** {rating}/5 ⭐
- **Comments:** {comments[:100]}{'...' if len(comments) > 100 else ''}
- **Email:** {user_email if user_email else 'Not provided'}
---
"""
                return result
            
            refresh_btn.click(
                fn=format_stats,
                outputs=admin_output
            )
            
            view_feedback_btn.click(
                fn=view_feedback_admin,
                outputs=admin_output
            )

if __name__ == "__main__":
    demo.launch()