File size: 169,301 Bytes
8bab08d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
"""
CX AI Agent - Enterprise B2B Sales Intelligence Platform

Automated AI-powered sales platform that:
1. Onboards client companies and builds their knowledge base
2. AI automatically discovers and researches prospect companies
3. AI finds decision makers at each prospect
4. Drafts personalized outreach emails
5. Generates handoff packet
s for sales teams
6. Provides AI chat for prospect engagement

Everything is AI-driven - no manual prospect entry needed.
"""

import os
import gradio as gr
import asyncio
import logging
import json
import base64
from pathlib import Path
from dotenv import load_dotenv
from datetime import datetime

# Load environment variables
load_dotenv()

# Set in-memory MCP mode for HF Spaces
os.environ["USE_IN_MEMORY_MCP"] = "true"

# Import MCP components
from mcp.registry import get_mcp_registry
from mcp.agents.autonomous_agent_hf import AutonomousMCPAgentHF

# Setup logging
import io
import sys

log_capture_string = io.StringIO()
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.StreamHandler(log_capture_string)
    ]
)
logger = logging.getLogger(__name__)

# Startup diagnostics
print("\n" + "="*80)
print("πŸš€ CX AI AGENT - ENTERPRISE B2B SALES INTELLIGENCE")
print("="*80)

# AI Mode - HuggingFace Inference API
# Uses Qwen/Qwen3-32B via nscale provider
HF_MODEL = os.getenv("HF_MODEL", "Qwen/Qwen3-32B")
HF_PROVIDER = os.getenv("HF_PROVIDER", "nscale")
# Session token storage - must be provided by user via UI
session_hf_token = {"token": None}

print(f"πŸ€– AI Mode: HuggingFace Inference API")
print(f"   Model: {HF_MODEL}")
print(f"   Provider: {HF_PROVIDER}")
print("ℹ️  HF_TOKEN must be entered by user in the Setup tab")

serper_key = os.getenv('SERPER_API_KEY')
if serper_key:
    print(f"βœ… SERPER_API_KEY loaded")
else:
    print("⚠️  SERPER_API_KEY not found - Web search limited")

space_id = os.getenv('SPACE_ID')
if space_id:
    print(f"πŸ“ Running in: {space_id}")
print("="*80 + "\n")

# Initialize MCP registry
try:
    mcp_registry = get_mcp_registry()
    print("βœ… AI Services initialized")
except Exception as e:
    print(f"❌ Initialization failed: {e}")
    raise


# Warm-up HuggingFace model on startup (optional, for faster first request)
def warmup_hf_model():
    """
    Send a dummy prompt to warm up the HuggingFace Inference API.
    This ensures the model is loaded and ready for the first real request.
    """
    token = session_hf_token.get("token")
    if not token:
        print("⏭️  Skipping model warm-up (token will be provided by user)")
        return

    try:
        import requests
        print(f"πŸ”₯ Warming up HuggingFace model ({HF_MODEL} via {HF_PROVIDER})...")

        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }

        # Add provider header
        if HF_PROVIDER and HF_PROVIDER != "hf-inference":
            headers["X-HF-Provider"] = HF_PROVIDER

        # Use the new router endpoint
        response = requests.post(
            "https://router.huggingface.co/v1/chat/completions",
            headers=headers,
            json={
                "model": HF_MODEL,
                "messages": [{"role": "user", "content": "Hello"}],
                "max_tokens": 10
            },
            timeout=30
        )

        if response.status_code == 200:
            print(f"βœ… Model warmed up and ready!")
        elif response.status_code == 402:
            print(f"ℹ️  Model {HF_MODEL} requires paid credits - will use fallback models")
        elif response.status_code == 404:
            print(f"ℹ️  Model {HF_MODEL} not found via {HF_PROVIDER} - will try on first use")
        else:
            print(f"ℹ️  Warm-up returned {response.status_code} - model will load on first use")
    except Exception as e:
        # Don't fail startup on warm-up error, just log it
        print(f"⚠️  Model warm-up skipped: {e}")


# Helper function to get current HF token (from UI or environment)
def get_hf_token(ui_token: str = None) -> str:
    """Get HF token from UI input, session storage, or environment"""
    if ui_token and ui_token.strip():
        # Update session storage with UI token
        session_hf_token["token"] = ui_token.strip()
        return ui_token.strip()
    return session_hf_token.get("token") or ""


# Session storage for SERPER API key - prioritizes user input over environment
session_serper_key = {"key": None}

def get_serper_key(ui_key: str = None) -> str:
    """Get SERPER API key from UI input, session storage, or environment.
    Priority: UI input > session storage > environment variable"""
    if ui_key and ui_key.strip():
        # Update session storage with UI key
        session_serper_key["key"] = ui_key.strip()
        return ui_key.strip()
    if session_serper_key.get("key"):
        return session_serper_key["key"]
    # Fall back to environment variable
    return os.getenv('SERPER_API_KEY') or ""

def update_search_service_key():
    """Update the search service singleton with current SERPER key"""
    from services.web_search import get_search_service
    key = get_serper_key()
    if key:
        service = get_search_service()
        service.api_key = key


# Run warm-up in background to not block startup
import threading
warmup_thread = threading.Thread(target=warmup_hf_model, daemon=True)
warmup_thread.start()


# ============================================================================
# KNOWLEDGE BASE - Session Storage
# ============================================================================
knowledge_base = {
    "client": {
        "name": None,
        "industry": None,
        "target_market": None,
        "products_services": None,
        "value_proposition": None,
        "ideal_customer_profile": None,
        "researched_at": None,
        "raw_research": None
    },
    "prospects": [],      # AI-discovered prospect companies
    "contacts": [],       # Decision makers found by AI
    "emails": [],         # Drafted emails
    "chat_history": [],   # AI chat conversation history
}


# ============================================================================
# ENTERPRISE CSS THEME - SIDEBAR SPA DESIGN
# ============================================================================
ENTERPRISE_CSS = """
/* ============== CSS VARIABLES ============== */
:root {
    --primary-blue: #0176D3;
    --primary-dark: #014486;
    --primary-light: #E5F3FE;
    --success-green: #2E844A;
    --success-light: #E6F4EA;
    --warning-orange: #DD7A01;
    --warning-light: #FEF3E2;
    --error-red: #EA001E;
    --error-light: #FDE7E9;
    --purple: #9050E9;
    --bg-primary: #FFFFFF;
    --bg-secondary: #F8FAFC;
    --bg-tertiary: #F1F5F9;
    --bg-hover: #E2E8F0;
    --text-primary: #1E293B;
    --text-secondary: #64748B;
    --text-tertiary: #94A3B8;
    --text-inverse: #FFFFFF;
    --border-color: #E2E8F0;
    --input-bg: #FFFFFF;
    --input-border: #CBD5E1;
    --card-shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06);
    --card-shadow-hover: 0 4px 6px rgba(0,0,0,0.1), 0 2px 4px rgba(0,0,0,0.06);
    --sidebar-width: 250px;
    --sidebar-collapsed: 64px;
    --header-height: 56px;
}

/* ============== DARK MODE ============== */
.dark {
    --primary-blue: #4DA6FF;
    --primary-dark: #0176D3;
    --primary-light: #1E3A5F;
    --success-green: #4ADE80;
    --success-light: #1A3A2A;
    --warning-orange: #FBBF24;
    --warning-light: #3D2E1A;
    --error-red: #F87171;
    --error-light: #3D1A1A;
    --purple: #A78BFA;
    --bg-primary: #1E293B;
    --bg-secondary: #0F172A;
    --bg-tertiary: #1E293B;
    --bg-hover: #334155;
    --text-primary: #F1F5F9;
    --text-secondary: #94A3B8;
    --text-tertiary: #64748B;
    --text-inverse: #0F172A;
    --border-color: #334155;
    --input-bg: #1E293B;
    --input-border: #475569;
    --card-shadow: 0 1px 3px rgba(0,0,0,0.3), 0 1px 2px rgba(0,0,0,0.2);
    --card-shadow-hover: 0 4px 6px rgba(0,0,0,0.3), 0 2px 4px rgba(0,0,0,0.2);
}

.dark .sidebar {
    background: linear-gradient(180deg, #0F172A 0%, #020617 100%);
}

.dark .gradio-container {
    background: var(--bg-secondary) !important;
}

/* ============== GLOBAL RESET ============== */
*, *::before, *::after { box-sizing: border-box !important; }

/* ============== GRADIO CONTAINER RESET ============== */
.gradio-container {
    max-width: 100% !important;
    width: 100% !important;
    padding: 0 !important;
    margin: 0 !important;
    background: var(--bg-secondary) !important;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
}

/* Hide Gradio footer and unnecessary elements */
footer { display: none !important; }
.gradio-container > div > div > div:first-child:empty { display: none !important; }

/* ============== SIDEBAR STYLES ============== */
.sidebar {
    position: fixed;
    left: 0;
    top: 0;
    width: var(--sidebar-width);
    height: 100vh;
    background: linear-gradient(180deg, #1E3A5F 0%, #0F2942 100%);
    display: flex;
    flex-direction: column;
    z-index: 1000;
    transition: width 0.3s ease, transform 0.3s ease;
    overflow: hidden;
}

.sidebar.collapsed { width: var(--sidebar-collapsed); }

.sidebar-header {
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    height: var(--header-height);
    flex-shrink: 0;
}

.sidebar-logo {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    flex-shrink: 0;
    object-fit: contain;
}

.sidebar-brand {
    color: white;
    font-weight: 700;
    font-size: 16px;
    white-space: nowrap;
    overflow: hidden;
    opacity: 1;
    transition: opacity 0.2s ease;
}

.sidebar.collapsed .sidebar-brand { opacity: 0; }

.sidebar-nav {
    flex: 1;
    padding: 12px 8px;
    overflow-y: auto;
    overflow-x: hidden;
}

.nav-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 12px;
    margin: 2px 0;
    border-radius: 8px;
    color: rgba(255,255,255,0.7);
    cursor: pointer;
    transition: all 0.15s ease;
    white-space: nowrap;
    overflow: hidden;
}

.nav-item:hover { background: rgba(255,255,255,0.1); color: white; }
.nav-item.active { background: var(--primary-blue); color: white; font-weight: 500; }

.nav-icon { font-size: 18px; width: 24px; text-align: center; flex-shrink: 0; }
.nav-text { font-size: 14px; opacity: 1; transition: opacity 0.2s ease; }
.sidebar.collapsed .nav-text { opacity: 0; }

.toggle-btn {
    position: absolute;
    right: -14px;
    top: 70px;
    width: 28px;
    height: 28px;
    background: white;
    border: 2px solid var(--border-color);
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: var(--text-secondary);
    z-index: 1001;
    box-shadow: var(--card-shadow);
    transition: transform 0.3s ease;
}

.toggle-btn:hover { background: var(--bg-tertiary); }
.sidebar.collapsed .toggle-btn { transform: rotate(180deg); }

/* ============== MAIN CONTENT AREA ============== */
.main-wrapper {
    margin-left: var(--sidebar-width) !important;
    width: calc(100% - var(--sidebar-width)) !important;
    max-width: calc(100vw - var(--sidebar-width)) !important;
    min-height: 100vh;
    padding: 20px;
    transition: margin-left 0.3s ease, width 0.3s ease;
    background: var(--bg-secondary);
    overflow-x: hidden;
    box-sizing: border-box !important;
}

.main-wrapper.expanded {
    margin-left: var(--sidebar-collapsed) !important;
    width: calc(100% - var(--sidebar-collapsed)) !important;
    max-width: calc(100vw - var(--sidebar-collapsed)) !important;
}

/* Ensure Gradio's inner containers don't overflow */
.main-wrapper > div,
.main-wrapper > div > div {
    max-width: 100% !important;
    overflow-x: hidden;
}

.content-area {
    max-width: 1200px;
    margin: 0 auto;
}

/* ============== PAGE SECTIONS ============== */
.page-section {
    display: none;
    animation: fadeIn 0.2s ease;
}

.page-section.active { display: block; }

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(8px); }
    to { opacity: 1; transform: translateY(0); }
}

/* ============== MOBILE STYLES ============== */
.mobile-header {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: var(--header-height);
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%);
    padding: 0 16px;
    align-items: center;
    gap: 12px;
    z-index: 999;
    box-shadow: var(--card-shadow);
}

.mobile-header .menu-btn {
    width: 36px;
    height: 36px;
    background: rgba(255,255,255,0.2);
    border: none;
    border-radius: 8px;
    color: white;
    font-size: 18px;
    cursor: pointer;
}

.mobile-header .title { color: white; font-weight: 600; font-size: 16px; }

.sidebar-overlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    z-index: 999;
}

/* ============== MOBILE RESPONSIVE ============== */
@media (max-width: 768px) {
    .sidebar {
        transform: translateX(-100%);
        width: var(--sidebar-width) !important;
    }
    .sidebar.mobile-open { transform: translateX(0); }
    .sidebar.mobile-open ~ .sidebar-overlay { display: block; }
    .toggle-btn { display: none; }

    .mobile-header { display: flex; }

    .main-wrapper {
        margin-left: 0 !important;
        width: 100% !important;
        max-width: 100vw !important;
        padding: 16px;
        padding-top: calc(var(--header-height) + 16px);
    }
}

@media (max-width: 480px) {
    .main-wrapper {
        padding: 12px;
        padding-top: calc(var(--header-height) + 12px);
        width: 100% !important;
    }
    .page-header { padding: 16px; }
    .page-title { font-size: 20px; }
}

/* ============== NAVIGATION BUTTONS ROW ============== */
.nav-buttons-row {
    /* Hidden visually but accessible to JS for click events */
    position: absolute;
    left: -9999px;
    top: -9999px;
    opacity: 0;
    pointer-events: none;
    gap: 8px;
    padding: 12px 16px;
    background: var(--bg-primary);
    border-radius: 12px;
    margin-bottom: 16px;
    box-shadow: var(--card-shadow);
    overflow-x: auto;
    flex-wrap: nowrap;
    -webkit-overflow-scrolling: touch;
}

.nav-buttons-row button {
    flex-shrink: 0;
    padding: 8px 14px !important;
    font-size: 13px !important;
    font-weight: 500 !important;
    border-radius: 8px !important;
    border: 1px solid var(--border-color) !important;
    background: var(--bg-secondary) !important;
    color: var(--text-primary) !important;
    transition: all 0.15s ease;
    white-space: nowrap;
}

.nav-buttons-row button:hover {
    background: var(--bg-hover) !important;
    border-color: var(--primary-blue) !important;
}

.nav-buttons-row button.active-nav-btn,
.nav-buttons-row button:first-child {
    background: var(--primary-blue) !important;
    color: white !important;
    border-color: var(--primary-blue) !important;
}

/* Show nav buttons on mobile/tablet */
@media (max-width: 768px) {
    .nav-buttons-row {
        position: static;
        left: auto;
        top: auto;
        opacity: 1;
        pointer-events: auto;
        display: flex;
    }
    .nav-buttons-row button:first-child {
        background: var(--primary-blue) !important;
        color: white !important;
    }
}

/* Page visibility control - ensure JS can toggle pages */
[id^="page-"] {
    flex-direction: column;
    width: 100%;
}
[id^="page-"].hidden {
    display: none !important;
}

/* Hide pages by default using CSS class */
.page-hidden {
    display: none !important;
}

.setup-required {
    background: var(--warning-light);
    border: 2px solid var(--warning-orange);
    border-radius: 12px;
    padding: 16px 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.setup-complete {
    background: var(--success-light);
    border: 2px solid var(--success-green);
    border-radius: 12px;
    padding: 16px 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.stat-card {
    background: var(--bg-primary);
    border-radius: 12px;
    padding: 20px 24px;
    box-shadow: var(--card-shadow);
    border-left: 4px solid var(--primary-blue);
    transition: all 0.2s ease;
}

.stat-card:hover { box-shadow: var(--card-shadow-hover); transform: translateY(-2px); }
.stat-card .stat-value { font-size: 28px; font-weight: 700; color: var(--text-primary); margin-bottom: 4px; }
.stat-card .stat-label { font-size: 13px; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; }

.action-card {
    background: var(--bg-primary);
    border-radius: 12px;
    padding: 24px;
    box-shadow: var(--card-shadow);
    margin-bottom: 16px;
    border: 1px solid var(--border-color);
}

.action-card h3 { margin: 0 0 12px 0; color: var(--text-primary); font-size: 18px; font-weight: 600; }
.action-card p { margin: 0 0 16px 0; color: var(--text-secondary); font-size: 14px; line-height: 1.6; }

/* ============== INFO BOX / HELP TIPS ============== */
.info-box {
    background: linear-gradient(135deg, var(--primary-light) 0%, #E8F4FD 100%);
    border: 1px solid var(--primary-blue);
    border-left: 4px solid var(--primary-blue);
    border-radius: 8px;
    padding: 16px 20px;
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
    align-items: flex-start;
}

.info-box.tip {
    background: linear-gradient(135deg, #FEF3C7 0%, #FEF9E7 100%);
    border-color: var(--warning-orange);
    border-left-color: var(--warning-orange);
}

.info-box.success {
    background: linear-gradient(135deg, var(--success-light) 0%, #E8F8ED 100%);
    border-color: var(--success-green);
    border-left-color: var(--success-green);
}

.info-box-icon {
    font-size: 20px;
    flex-shrink: 0;
    margin-top: 2px;
}

.info-box-content {
    flex: 1;
}

.info-box-title {
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 4px;
    font-size: 14px;
}

.info-box-text {
    color: var(--text-secondary);
    font-size: 13px;
    line-height: 1.5;
    margin: 0;
}

.info-box-text ul {
    margin: 8px 0 0 0;
    padding-left: 18px;
}

.info-box-text li {
    margin-bottom: 4px;
}

.dark .info-box {
    background: linear-gradient(135deg, rgba(1, 118, 211, 0.15) 0%, rgba(1, 118, 211, 0.08) 100%);
}

.dark .info-box.tip {
    background: linear-gradient(135deg, rgba(251, 191, 36, 0.15) 0%, rgba(251, 191, 36, 0.08) 100%);
}

.dark .info-box.success {
    background: linear-gradient(135deg, rgba(46, 132, 74, 0.15) 0%, rgba(46, 132, 74, 0.08) 100%);
}

/* Collapsible help section */
.help-toggle {
    background: none;
    border: none;
    color: var(--primary-blue);
    cursor: pointer;
    font-size: 13px;
    padding: 4px 8px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 8px;
}

.help-toggle:hover {
    text-decoration: underline;
}

button.primary {
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%) !important;
    color: white !important;
    border: none !important;
    border-radius: 8px !important;
    padding: 12px 28px !important;
    font-size: 15px !important;
    font-weight: 600 !important;
    min-height: 44px !important;
}

button.secondary {
    background: var(--bg-primary) !important;
    color: var(--primary-blue) !important;
    border: 2px solid var(--primary-blue) !important;
    border-radius: 8px !important;
    padding: 8px 16px !important;
    font-weight: 600 !important;
}

button.stop {
    background: var(--error-red) !important;
    color: white !important;
    border: none !important;
}

input[type="text"], textarea {
    background: var(--input-bg) !important;
    color: var(--text-primary) !important;
    border: 2px solid var(--input-border) !important;
    border-radius: 8px !important;
    padding: 12px 16px !important;
    font-size: 15px !important;
}

.prospect-card {
    background: var(--bg-primary);
    border-radius: 12px;
    margin-bottom: 12px;
    border: 1px solid var(--border-color);
    box-shadow: var(--card-shadow);
    overflow: hidden;
}

.prospect-card-header {
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    transition: background 0.2s ease;
}

.prospect-card-header:hover { background: var(--bg-hover); }

.prospect-card-title { font-size: 16px; font-weight: 600; color: var(--text-primary); }

.prospect-card-badge { padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; }
.badge-new { background: var(--primary-light); color: var(--primary-blue); }
.badge-researched { background: var(--success-light); color: var(--success-green); }

.prospect-card-details {
    padding: 0 20px 20px 20px;
    border-top: 1px solid var(--border-color);
    background: var(--bg-secondary);
}

.detail-section { margin-top: 16px; }
.detail-section h4 { font-size: 13px; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; margin: 0 0 8px 0; }
.detail-section p, .detail-section li { font-size: 14px; color: var(--text-primary); line-height: 1.6; margin: 4px 0; }

.empty-state { text-align: center; padding: 60px 20px; color: var(--text-secondary); }
.empty-state-icon { font-size: 56px; margin-bottom: 16px; opacity: 0.6; }
.empty-state-title { font-size: 18px; font-weight: 600; color: var(--text-primary); margin-bottom: 8px; }
.empty-state-desc { font-size: 14px; color: var(--text-secondary); }

/* Progress Log Styling */
.progress-container {
    background: var(--bg-secondary);
    border-radius: 12px;
    padding: 16px;
    margin: 12px 0;
    border: 1px solid var(--border-color);
}

.progress-header {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border-color);
}

.progress-section {
    background: var(--bg-tertiary);
    border-radius: 8px;
    padding: 12px 16px;
    margin: 8px 0;
    border-left: 3px solid var(--primary-blue);
}

.progress-item {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 6px 0;
    font-size: 14px;
    line-height: 1.5;
}

.progress-icon {
    flex-shrink: 0;
    width: 20px;
    text-align: center;
}

.progress-text {
    flex: 1;
    color: var(--text-primary);
}

.progress-success {
    color: var(--success-green);
    font-weight: 500;
}

.progress-info {
    color: var(--primary-blue);
}

.progress-warning {
    color: var(--warning-orange);
}

.progress-detail {
    font-size: 12px;
    color: var(--text-secondary);
    margin-left: 30px;
    padding: 4px 0;
}

/* Collapsible Progress Log */
.progress-accordion {
    background: var(--bg-secondary);
    border-radius: 12px;
    border: 1px solid var(--border-color);
    margin: 12px 0;
    overflow: hidden;
}

.progress-accordion-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 18px;
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%);
    color: white;
    cursor: pointer;
    user-select: none;
    transition: background 0.2s ease;
}

.progress-accordion-header:hover {
    background: linear-gradient(135deg, var(--primary-dark) 0%, var(--primary-blue) 100%);
}

.progress-accordion-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-weight: 600;
    font-size: 15px;
}

.progress-accordion-toggle {
    font-size: 12px;
    opacity: 0.9;
    transition: transform 0.3s ease;
}

.progress-accordion.collapsed .progress-accordion-toggle {
    transform: rotate(-90deg);
}

.progress-accordion-body {
    max-height: 400px;
    overflow-y: auto;
    padding: 16px;
    transition: max-height 0.3s ease, padding 0.3s ease;
}

.progress-accordion.collapsed .progress-accordion-body {
    max-height: 0;
    padding: 0 16px;
    overflow: hidden;
}

/* Loading spinner */
.loading-spinner {
    display: inline-block;
    width: 18px;
    height: 18px;
    border: 2px solid rgba(255,255,255,0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* MCP Tool Call Badge */
.mcp-tool-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
    color: white;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
    margin-left: 8px;
}

.search-query-badge {
    display: inline-block;
    background: var(--bg-tertiary);
    color: var(--text-primary);
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 12px;
    font-family: monospace;
    margin-left: 8px;
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.progress-step {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 10px 0;
    border-bottom: 1px solid var(--border-color);
}

.progress-step:last-child {
    border-bottom: none;
}

.progress-step-icon {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    flex-shrink: 0;
}

.progress-step-icon.loading {
    background: var(--primary-blue);
}

.progress-step-icon.success {
    background: var(--success-green);
}

.progress-step-icon.tool {
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
}

.progress-step-icon.error {
    background: var(--error-red, #e74c3c);
}

.progress-step-icon.warning {
    background: var(--warning-orange, #f39c12);
}

.progress-step-content {
    flex: 1;
}

.progress-step-title {
    font-weight: 500;
    color: var(--text-primary);
    font-size: 14px;
}

.progress-step-detail {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 2px;
}

.progress-summary {
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-dark) 100%);
    color: white;
    border-radius: 8px;
    padding: 16px;
    margin-top: 16px;
}

.progress-summary h3 {
    margin: 0 0 12px 0;
    font-size: 16px;
}

.progress-summary table {
    width: 100%;
    border-collapse: collapse;
}

.progress-summary td {
    padding: 6px 8px;
    border-bottom: 1px solid rgba(255,255,255,0.2);
}

.progress-summary td:first-child {
    font-weight: 500;
}

.progress-summary td:last-child {
    text-align: right;
    font-weight: 600;
}

.footer { text-align: center; padding: 24px; color: var(--text-secondary); border-top: 1px solid var(--border-color); margin-top: 32px; }

.prose { max-width: none !important; }
.prose code { background: var(--bg-tertiary) !important; padding: 2px 6px !important; border-radius: 4px !important; }
.prose pre { background: var(--bg-tertiary) !important; border-radius: 8px !important; padding: 16px !important; }

.dark input, .dark textarea {
    background: var(--input-bg) !important;
    color: var(--text-primary) !important;
    border-color: var(--input-border) !important;
}
.dark label, .dark .prose, .dark .prose p { color: var(--text-primary) !important; }
.dark .page-header, .dark .action-card, .dark .form-section, .dark .stat-card {
    background: var(--bg-primary) !important;
}

/* ============== COMPONENT RESPONSIVE STYLES ============== */

/* Stats grid */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 20px;
}

/* Content grid for two-column layouts */
.content-grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 20px;
}

@media (max-width: 900px) {
    .content-grid {
        grid-template-columns: 1fr;
    }
}

/* Form layouts */
.form-section {
    background: var(--bg-primary);
    border-radius: 12px;
    padding: 20px;
    box-shadow: var(--card-shadow);
    margin-bottom: 16px;
}

/* Chatbot adjustments */
.chatbot, [class*="chatbot"] {
    height: 400px !important;
    border-radius: 12px !important;
}

@media (max-width: 768px) {
    .chatbot, [class*="chatbot"] {
        height: 300px !important;
    }

    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }

    .stat-card {
        padding: 12px !important;
    }

    .stat-value { font-size: 20px !important; }
    .stat-label { font-size: 10px !important; }

    .action-card {
        padding: 16px !important;
    }

    .action-card h3 { font-size: 16px !important; }
}

@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr 1fr;
        gap: 8px;
    }

    .chatbot, [class*="chatbot"] {
        height: 250px !important;
    }
}

/* Print styles */
@media print {
    .sidebar, .mobile-header, .sidebar-overlay { display: none !important; }
    .main-wrapper { margin-left: 0 !important; }
}
"""


# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

def get_stat_html(value: str, label: str, color: str) -> str:
    return f"""
    <div class="stat-card" style="border-left-color: {color};">
        <div class="stat-value">{value}</div>
        <div class="stat-label">{label}</div>
    </div>
    """


def get_client_status_html() -> str:
    if knowledge_base["client"]["name"]:
        return f"""
        <div class="setup-complete">
            <span style="font-size: 24px;">βœ…</span>
            <div>
                <strong style="color: var(--success-green);">Client Profile Active</strong>
                <p style="margin: 4px 0 0 0; font-size: 13px; color: var(--text-secondary);">
                    AI is finding prospects for <strong>{knowledge_base["client"]["name"]}</strong>
                </p>
            </div>
        </div>
        """
    return """
    <div class="setup-required">
        <span style="font-size: 24px;">⚠️</span>
        <div>
            <strong style="color: var(--warning-orange);">Setup Required</strong>
            <p style="margin: 4px 0 0 0; font-size: 13px; color: var(--text-secondary);">
                Go to <strong>Setup</strong> tab to enter your company name and start AI prospect discovery.
            </p>
        </div>
    </div>
    """


def get_dashboard_stats():
    return (
        get_stat_html(str(len(knowledge_base["prospects"])), "Prospects Found", "var(--primary-blue)"),
        get_stat_html(str(len(knowledge_base["contacts"])), "Decision Makers", "var(--success-green)"),
        get_stat_html(str(len(knowledge_base["emails"])), "Emails Drafted", "var(--warning-orange)"),
        get_client_status_html()
    )


def merge_to_knowledge_base(prospects_found: list, contacts_found: list, emails_drafted: list):
    """Merge found data to knowledge base with deduplication"""
    global knowledge_base

    # Deduplicate prospects by name/domain
    existing_prospect_keys = set()
    for p in knowledge_base["prospects"]:
        key = (p.get("name", "").lower(), p.get("domain", "").lower())
        existing_prospect_keys.add(key)

    for p in prospects_found:
        key = (p.get("name", "").lower(), p.get("domain", "").lower())
        if key not in existing_prospect_keys:
            knowledge_base["prospects"].append(p)
            existing_prospect_keys.add(key)

    # Deduplicate contacts by email
    existing_emails = set(c.get("email", "").lower() for c in knowledge_base["contacts"])
    for c in contacts_found:
        email = c.get("email", "").lower()
        if email and email not in existing_emails:
            knowledge_base["contacts"].append(c)
            existing_emails.add(email)

    # Deduplicate emails by to+subject
    existing_email_keys = set()
    for e in knowledge_base["emails"]:
        key = (e.get("to", "").lower(), e.get("subject", "").lower())
        existing_email_keys.add(key)

    for e in emails_drafted:
        key = (e.get("to", "").lower(), e.get("subject", "").lower())
        if key not in existing_email_keys:
            knowledge_base["emails"].append(e)
            existing_email_keys.add(key)


def get_prospects_html() -> str:
    if not knowledge_base["prospects"]:
        return """
        <div class="empty-state">
            <div class="empty-state-icon">🎯</div>
            <div class="empty-state-title">No prospects discovered yet</div>
            <div class="empty-state-desc">Complete the Setup and click "Find Prospects" to let AI discover potential customers</div>
        </div>
        """

    html = ""
    for p in reversed(knowledge_base["prospects"]):
        status_class = "badge-researched" if p.get("research_complete") else "badge-new"
        status_text = "RESEARCHED" if p.get("research_complete") else "DISCOVERED"

        # Build contacts list (case-insensitive matching)
        contacts_html = ""
        p_name_lower = p.get("name", "").lower()
        prospect_contacts = [c for c in knowledge_base["contacts"]
                           if p_name_lower in c.get("company", "").lower()
                           or c.get("company", "").lower() in p_name_lower]
        if prospect_contacts:
            contacts_html = "<ul style='margin: 0; padding-left: 20px;'>"
            for c in prospect_contacts:
                contacts_html += f"<li><strong>{c.get('name', 'Unknown')}</strong> - {c.get('title', 'Unknown')}"
                if c.get('email'):
                    contacts_html += f" ({c.get('email')})"
                contacts_html += "</li>"
            contacts_html += "</ul>"
        else:
            contacts_html = "<p style='color: var(--text-secondary);'>No contacts found yet</p>"

        html += f"""
        <details class="prospect-card">
            <summary class="prospect-card-header">
                <span class="prospect-card-title">🏒 {p.get("name", "Unknown")}</span>
                <span class="prospect-card-badge {status_class}">{status_text}</span>
            </summary>
            <div class="prospect-card-details">
                <div class="detail-section">
                    <h4>πŸ“‹ Company Summary</h4>
                    <p>{p.get("summary", "No summary available")}</p>
                </div>
                <div class="detail-section">
                    <h4>🏭 Industry</h4>
                    <p>{p.get("industry") or "Technology & Services"}</p>
                </div>
                <div class="detail-section">
                    <h4>🎯 Why They're a Good Fit</h4>
                    <p>{p.get("fit_reason", "Matches target customer profile")}</p>
                </div>
                <div class="detail-section">
                    <h4>πŸ‘₯ Decision Makers ({len(prospect_contacts)})</h4>
                    {contacts_html}
                </div>
                <div class="detail-section">
                    <h4>βœ‰οΈ Outreach Status</h4>
                    <p>{'βœ… Email drafted' if p.get("email_drafted") else '⏳ Pending'}</p>
                </div>
                <div class="detail-section">
                    <h4>πŸ“… Discovered</h4>
                    <p>{p.get("discovered_at") or datetime.now().strftime("%Y-%m-%d %H:%M")}</p>
                </div>
            </div>
        </details>
        """

    return html


def get_emails_html() -> str:
    if not knowledge_base["emails"]:
        return """
        <div class="empty-state">
            <div class="empty-state-icon">βœ‰οΈ</div>
            <div class="empty-state-title">No emails drafted yet</div>
            <div class="empty-state-desc">AI will draft personalized emails after discovering prospects</div>
        </div>
        """

    html = ""
    for e in reversed(knowledge_base["emails"]):
        body_display = e.get("body", "").replace("\n", "<br>")
        html += f"""
        <details class="prospect-card">
            <summary class="prospect-card-header">
                <span class="prospect-card-title">βœ‰οΈ {e.get("subject", "No subject")[:50]}{'...' if len(e.get("subject", "")) > 50 else ''}</span>
                <span class="prospect-card-badge badge-new">DRAFT</span>
            </summary>
            <div class="prospect-card-details">
                <div class="detail-section">
                    <h4>🏒 Prospect</h4>
                    <p>{e.get("prospect_company", "Unknown")}</p>
                </div>
                <div class="detail-section">
                    <h4>πŸ“§ To</h4>
                    <p>{e.get("to", "Not specified")}</p>
                </div>
                <div class="detail-section">
                    <h4>πŸ“ Subject</h4>
                    <p><strong>{e.get("subject", "No subject")}</strong></p>
                </div>
                <div class="detail-section">
                    <h4>πŸ“„ Email Body</h4>
                    <div style="background: var(--bg-tertiary); padding: 16px; border-radius: 8px; margin-top: 8px;">
                        <p style="white-space: pre-wrap; margin: 0;">{body_display}</p>
                    </div>
                </div>
            </div>
        </details>
        """
    return html


def get_contacts_html() -> str:
    if not knowledge_base["contacts"]:
        return """
        <div class="empty-state">
            <div class="empty-state-icon">πŸ‘₯</div>
            <div class="empty-state-title">No contacts found yet</div>
            <div class="empty-state-desc">AI will find decision makers when discovering prospects</div>
        </div>
        """

    html = """
    <div style="background: var(--success-bg, #d4edda); border: 1px solid var(--success-border, #c3e6cb); border-radius: 8px; padding: 12px 16px; margin-bottom: 16px;">
        <div style="font-size: 13px; color: var(--success-text, #155724);">
            <strong>βœ… Verified Contacts:</strong> All contacts shown here were found through web searches of LinkedIn profiles,
            company team pages, and public directories. Only contacts with <strong>verified email addresses</strong> found on the web are displayed.
        </div>
    </div>
    """
    for c in reversed(knowledge_base["contacts"]):
        source = c.get("source", "web_search")
        source_label = {
            "web_search": "Found via web search",
            "linkedin": "Found via LinkedIn",
            "team_page": "Found on company page",
            "web_search_and_scraping": "Verified from web"
        }.get(source, "Verified")
        html += f"""
        <div class="prospect-card" style="padding: 16px 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <div style="font-weight: 600; color: var(--text-primary);">πŸ‘€ {c.get("name", "Unknown")}</div>
                    <div style="font-size: 13px; color: var(--text-secondary); margin-top: 4px;">{c.get("title", "Unknown title")}</div>
                    <div style="font-size: 13px; color: var(--text-secondary);">🏒 {c.get("company", "Unknown company")}</div>
                    {f'<div style="font-size: 13px; color: var(--primary-blue); margin-top: 4px;">πŸ“§ {c.get("email")}</div>' if c.get("email") else ''}
                </div>
                <span class="prospect-card-badge badge-engaged">VERIFIED</span>
            </div>
            <div style="font-size: 11px; color: var(--text-secondary); margin-top: 8px;">{source_label}</div>
        </div>
        """
    return html


def reset_all_data():
    global knowledge_base
    knowledge_base = {
        "client": {"name": None, "industry": None, "target_market": None, "products_services": None,
                   "value_proposition": None, "ideal_customer_profile": None, "researched_at": None, "raw_research": None},
        "prospects": [], "contacts": [], "emails": [], "chat_history": []
    }
    stats = get_dashboard_stats()
    return (stats[0], stats[1], stats[2], stats[3], get_prospects_html(), get_emails_html(),
            get_contacts_html(), "", "*Enter your company name to begin.*", "*Click 'Find Prospects' after setup.*")


# ============================================================================
# CLIENT SETUP - Research the user's company
# ============================================================================
async def setup_client_company(company_name: str, hf_token_input: str, serper_key_input: str = "", progress=gr.Progress()):
    global knowledge_base

    if not company_name or not company_name.strip():
        yield "⚠️ Please enter your company name."
        return

    # Get HF token from UI input or environment
    token = get_hf_token(hf_token_input)
    if not token:
        yield "⚠️ **HF_TOKEN Required**: Please enter your HuggingFace token in the Setup tab.\n\nGet a free token at: https://huggingface.co/settings/tokens"
        return

    # Store SERPER API key if provided (prioritize user input)
    if serper_key_input and serper_key_input.strip():
        get_serper_key(serper_key_input)
    # Update the search service with current key
    update_search_service_key()

    company_name = company_name.strip()

    # Initialize progress log with HTML styling
    output = f"""<div class="progress-container">
<div class="progress-header">🏒 Setting Up: {company_name}</div>
<div class="progress-section">
<div class="progress-item"><span class="progress-icon">⏳</span><span class="progress-text">Building knowledge base...</span></div>
"""
    yield output
    progress(0.1, desc="Initializing...")

    try:
        # Initialize HuggingFace agent with nscale provider
        agent = AutonomousMCPAgentHF(
            mcp_registry=mcp_registry,
            hf_token=token,
            provider=HF_PROVIDER,
            model=HF_MODEL
        )
        output += f"""<div class="progress-item"><span class="progress-icon">βœ…</span><span class="progress-text progress-success">AI Agent initialized ({agent.model})</span></div>
"""
        yield output
        progress(0.2)
    except Exception as e:
        yield f"""<div class="progress-item"><span class="progress-icon">❌</span><span class="progress-text" style="color: var(--error-red);">Agent init failed: {e}</span></div></div></div>"""
        return

    task = f"""Research {company_name} to understand their business. Use search_web to find information about:
1. What {company_name} does - their products/services
2. Their target market and ideal customers
3. Their industry and market position
4. Their value proposition
5. What type of companies would be good prospects for them

Use the save_company tool to save information about {company_name}:
- company_id: "{company_name.lower().replace(' ', '_')}"
- name: "{company_name}"
- domain: their website domain
- industry: their industry
- description: brief company description

After researching, provide a comprehensive summary of:
- What {company_name} does
- Who their ideal customers are
- What industries/company types would benefit from their services

This is OUR company - we need this information to find matching prospects."""

    last_research = ""  # Track last AI response for fallback
    search_results_summary = []  # Capture actual search results
    search_count = 0
    try:
        async for event in agent.run(task, max_iterations=12):
            event_type = event.get("type")
            if event_type == "model_loaded":
                output += f"""<div class="progress-item"><span class="progress-icon">🧠</span><span class="progress-text">{event.get('message', 'Model loaded')}</span></div>
"""
                yield output
            elif event_type == "iteration_start":
                output += f"""<div class="progress-item"><span class="progress-icon">πŸ’­</span><span class="progress-text progress-info">{event.get('message', 'Thinking...')}</span></div>
"""
                yield output
            elif event_type == "tool_call":
                tool = event.get("tool", "")
                if tool == "search_web":
                    output += f"""<div class="progress-item"><span class="progress-icon">πŸ”</span><span class="progress-text">Searching for {company_name}...</span></div>
"""
                    search_count += 1
                elif tool == "search_news":
                    output += f"""<div class="progress-item"><span class="progress-icon">πŸ“°</span><span class="progress-text">Finding news...</span></div>
"""
                elif tool in ["save_company", "save_fact"]:
                    output += f"""<div class="progress-item"><span class="progress-icon">πŸ’Ύ</span><span class="progress-text">Saving information...</span></div>
"""
                yield output
                progress(0.3 + min(search_count * 0.1, 0.4))
            elif event_type == "tool_result":
                tool = event.get("tool", "")
                result = event.get("result", {})
                if tool in ["search_web", "search_news"]:
                    count = result.get("count", 0) if isinstance(result, dict) else 0
                    output += f"""<div class="progress-detail">βœ… Found {count} results</div>
"""
                    # Capture search results for building a summary
                    if isinstance(result, dict) and result.get("results"):
                        for r in result.get("results", [])[:3]:  # Top 3 results
                            if isinstance(r, dict):
                                title = r.get("title", "")
                                # Try multiple field names for snippet/body
                                snippet = r.get("body", r.get("text", r.get("snippet", r.get("description", ""))))
                                if title and title not in str(search_results_summary):
                                    if snippet:
                                        search_results_summary.append(f"- **{title}**: {snippet[:200]}..." if len(snippet) > 200 else f"- **{title}**: {snippet}")
                                    else:
                                        search_results_summary.append(f"- **{title}**")
                yield output
            elif event_type == "thought":
                # Capture AI thoughts for potential use as research summary
                thought = event.get("thought", "")
                message = event.get("message", "")
                # Filter out any HTML/footer content that might leak through
                if thought and not thought.startswith("CX AI Agent") and "Powered by AI" not in thought and not thought.startswith("[Processing:"):
                    if len(thought) > len(last_research):
                        last_research = thought
                        logger.info(f"Captured research thought: {thought[:100]}...")
                    # Also show progress in output
                    output += f"πŸ“ {message}\n"
                    yield output
                elif message:
                    # Show reasoning progress even if thought is minimal
                    output += f"πŸ€” {message}\n"
                    yield output
            elif event_type == "agent_complete":
                final_answer = event.get("final_answer", "")
                # Filter out HTML footer that might leak through
                if not final_answer or "CX AI Agent" in final_answer or "Powered by AI" in final_answer:
                    final_answer = last_research
                # If still no answer, build from search results
                if not final_answer and search_results_summary:
                    final_answer = f"**{company_name}** - Research findings:\n\n" + "\n".join(search_results_summary[:10])
                if not final_answer:
                    final_answer = f"Research completed for {company_name}. The AI gathered information about the company. Ready to find prospects."
                knowledge_base["client"] = {
                    "name": company_name,
                    "raw_research": final_answer,
                    "researched_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                }
                output += f"\n---\n\n## βœ… {company_name} Profile Complete!\n\n"
                output += "**Next step:** Go to the **Discovery** tab and click **'πŸ” Find Prospects & Contacts'** to let AI discover potential customers.\n\n"

                # Show search results if we have them
                if search_results_summary:
                    output += "---\n\n### πŸ” Search Results Found\n\n"
                    output += "\n".join(search_results_summary[:8])
                    output += "\n\n"

                output += f"---\n\n### πŸ“‹ Research Summary\n\n{final_answer}"
                yield output
                progress(1.0)
                return
            elif event_type == "agent_max_iterations":
                # Still save what we have
                final_answer = last_research
                if not final_answer and search_results_summary:
                    final_answer = f"**{company_name}** - Research findings:\n\n" + "\n".join(search_results_summary[:10])
                if not final_answer:
                    final_answer = f"Research completed for {company_name}. Ready to find prospects."
                knowledge_base["client"] = {
                    "name": company_name,
                    "raw_research": final_answer,
                    "researched_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                }
                output += f"\n---\n\n## βœ… {company_name} Profile Complete!\n\n"
                output += "**Next step:** Go to the **Discovery** tab and click **'πŸ” Find Prospects & Contacts'** to let AI discover potential customers.\n\n"
                if final_answer:
                    output += f"---\n\n### πŸ“‹ Research Summary\n\n{final_answer}"
                yield output
                progress(1.0)
                return
            elif event_type == "agent_error":
                error_msg = event.get("error", "Unknown error")
                # Still save basic profile so user can proceed
                knowledge_base["client"] = {
                    "name": company_name,
                    "raw_research": last_research or f"{company_name} - manual research may be needed.",
                    "researched_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                }
                output += f"\n⚠️ AI encountered an issue: {error_msg}\n"
                output += f"\n---\n\n## ⚠️ {company_name} Setup (Partial)\n\n"
                output += "**Note:** Some research may be incomplete. You can still proceed to find prospects.\n\n"
                yield output
                progress(1.0)
                return
    except Exception as e:
        # Save basic profile on exception so user can still proceed
        knowledge_base["client"] = {
            "name": company_name,
            "raw_research": last_research or f"{company_name} - setup interrupted.",
            "researched_at": datetime.now().strftime("%Y-%m-%d %H:%M")
        }
        output += f"\n⚠️ Error: {e}\n"
        output += f"\n**Note:** Basic profile saved. You can still try to find prospects.\n"
        yield output
        return

    # If we get here without returning, the loop completed without agent_complete/max_iterations/error
    # This means the agent just stopped - save what we have
    if not knowledge_base["client"]["name"]:
        final_answer = last_research
        if not final_answer and search_results_summary:
            final_answer = f"**{company_name}** - Research findings:\n\n" + "\n".join(search_results_summary[:10])
        if not final_answer:
            final_answer = f"Research completed for {company_name}. Ready to find prospects."
        knowledge_base["client"] = {
            "name": company_name,
            "raw_research": final_answer,
            "researched_at": datetime.now().strftime("%Y-%m-%d %H:%M")
        }
        output += f"\n---\n\n## βœ… {company_name} Profile Complete!\n\n"
        output += "**Next step:** Go to the **Discovery** tab and click **'πŸ” Find Prospects & Contacts'** to let AI discover potential customers.\n\n"
        output += f"---\n\n### πŸ“‹ Research Summary\n\n{final_answer}"
        yield output


# ============================================================================
# AI PROSPECT DISCOVERY - Automatically find prospects
# ============================================================================
async def discover_prospects(num_prospects: int, progress=gr.Progress()):
    global knowledge_base

    if not knowledge_base["client"]["name"]:
        yield "⚠️ **Setup Required**: Please go to Setup tab and enter your company name first."
        return

    # Use session token (set in Setup tab)
    token = session_hf_token.get("token")
    if not token:
        yield "⚠️ **HF_TOKEN Required**: Please enter your HuggingFace token in the **Setup** tab first.\n\nGet a free token at: https://huggingface.co/settings/tokens"
        return

    # Ensure search service has current SERPER key
    update_search_service_key()

    client_name = knowledge_base["client"]["name"]
    client_info = knowledge_base["client"].get("raw_research", "")

    # Initialize progress log with collapsible accordion
    progress_steps = []

    def build_accordion(steps, is_loading=True, summary_html=""):
        """Build the collapsible accordion HTML"""
        status_text = "Processing..." if is_loading else "Complete"
        spinner = '<div class="loading-spinner"></div>' if is_loading else 'βœ…'

        steps_html = ""
        for step in steps:
            icon_class = step.get("icon_class", "tool")
            steps_html += f'''<div class="progress-step">
                <div class="progress-step-icon {icon_class}">{step.get("icon", "πŸ”§")}</div>
                <div class="progress-step-content">
                    <div class="progress-step-title">{step.get("title", "")}</div>
                    {f'<div class="progress-step-detail">{step.get("detail", "")}</div>' if step.get("detail") else ""}
                </div>
            </div>'''

        return f'''<div class="progress-accordion" id="discovery-progress">
            <div class="progress-accordion-header" onclick="this.parentElement.classList.toggle('collapsed')">
                <div class="progress-accordion-title">
                    {spinner}
                    <span>πŸ” AI Discovery Progress - {status_text}</span>
                </div>
                <span class="progress-accordion-toggle">β–Ό</span>
            </div>
            <div class="progress-accordion-body">
                {steps_html}
            </div>
        </div>
        {summary_html}'''

    progress_steps.append({"icon": "⏳", "icon_class": "loading", "title": "Initializing AI agent...", "detail": f"Preparing to find prospects for {client_name}"})
    yield build_accordion(progress_steps)
    progress(0.1)

    try:
        # Initialize HuggingFace agent with nscale provider
        agent = AutonomousMCPAgentHF(
            mcp_registry=mcp_registry,
            hf_token=token,
            provider=HF_PROVIDER,
            model=HF_MODEL
        )
        progress_steps[-1] = {"icon": "βœ…", "icon_class": "success", "title": "AI Agent initialized", "detail": f"Model: {agent.model}"}
        yield build_accordion(progress_steps)
        progress(0.2)
    except Exception as e:
        progress_steps[-1] = {"icon": "❌", "icon_class": "error", "title": "Agent initialization failed", "detail": str(e)[:100]}
        yield build_accordion(progress_steps, is_loading=False)
        return

    # Build a concise industry description from client research
    # This helps the discovery tool generate better search queries
    client_industry_desc = f"{client_name}"
    if client_info:
        # Extract key info - first 200 chars or first sentence
        info_snippet = client_info[:300].split('.')[0] if '.' in client_info[:300] else client_info[:200]
        client_industry_desc = f"{client_name} - {info_snippet}"

    task = f"""You are an AI sales agent finding prospects for {client_name}.

About {client_name}:
{client_info}

USE THE discover_prospects_with_contacts TOOL - it handles everything automatically:
- Searches for potential prospect companies (CUSTOMERS who would buy from {client_name})
- Finds verified contacts for each (LinkedIn, company websites, directories, etc.)
- ONLY saves prospects that have real verified contacts
- Keeps searching until target is met or max attempts reached
- Skips companies without contacts automatically

STEP 1: Call discover_prospects_with_contacts with accurate industry description:
{{"client_company": "{client_name}", "client_industry": "{client_industry_desc}", "target_prospects": {num_prospects}, "target_titles": ["CEO", "Founder", "VP Sales", "CTO", "Head of Sales"]}}

STEP 2: After discovery completes, for each prospect with contacts, draft personalized email:
- Use send_email tool with the REAL contact info returned
- to: actual verified email
- subject: Reference {client_name} AND the prospect's business
- body: Personalized email mentioning the contact by name and specific facts about their company
- prospect_id: the prospect_id from discovery results

IMPORTANT:
- The discover_prospects_with_contacts tool does ALL the hard work
- It will check multiple companies until it finds {num_prospects} with verified contacts
- Only prospects WITH contacts are saved (no useless data)
- NEVER invent contact names or emails - only use what the tool returns

After the tool completes, provide a summary of:
- Prospects saved (with verified contacts)
- Total contacts found
- Companies checked vs skipped
- Emails drafted"""

    prospects_found = []
    contacts_found = []
    emails_drafted = []
    search_results_for_prospects = []  # Capture search results to extract prospects

    # Track pending tool calls to capture data
    pending_prospect = None
    pending_contact = None
    current_prospect_name = None  # Track which prospect we're working on

    try:
        iteration = 0
        last_final_answer = ""  # Track the last complete response from AI
        async for event in agent.run(task, max_iterations=25):
            event_type = event.get("type")
            iteration += 1
            progress_pct = min(0.2 + (iteration * 0.03), 0.95)

            if event_type == "model_loaded":
                progress_steps.append({"icon": "🧠", "icon_class": "success", "title": event.get('message', 'Model loaded'), "detail": ""})
                yield build_accordion(progress_steps)
            elif event_type == "iteration_start":
                progress_steps.append({"icon": "πŸ’­", "icon_class": "loading", "title": "AI is thinking...", "detail": event.get('message', '')})
                yield build_accordion(progress_steps)
            elif event_type == "tool_call":
                tool = event.get("tool", "")
                tool_input = event.get("input", {})

                if tool == "search_web":
                    query = tool_input.get("query", "") if isinstance(tool_input, dict) else ""
                    progress_steps.append({
                        "icon": "πŸ”",
                        "icon_class": "tool",
                        "title": f'<span class="mcp-tool-badge">MCP</span> search_web',
                        "detail": f'Query: "{query[:60]}{"..." if len(query) > 60 else ""}"'
                    })
                elif tool == "search_news":
                    progress_steps.append({
                        "icon": "πŸ“°",
                        "icon_class": "tool",
                        "title": f'<span class="mcp-tool-badge">MCP</span> search_news',
                        "detail": "Searching for recent news..."
                    })
                elif tool == "discover_prospects_with_contacts":
                    target = tool_input.get("target_prospects", num_prospects) if isinstance(tool_input, dict) else num_prospects
                    progress_steps.append({
                        "icon": "πŸš€",
                        "icon_class": "tool",
                        "title": f'<span class="mcp-tool-badge">MCP</span> discover_prospects_with_contacts',
                        "detail": f"Finding {target} prospects with verified contacts..."
                    })
                elif tool == "save_prospect":
                    if isinstance(tool_input, dict):
                        company = tool_input.get("company_name", "Unknown")
                        current_prospect_name = company  # Track current prospect
                        progress_steps.append({
                            "icon": "🎯",
                            "icon_class": "success",
                            "title": f"Found prospect: <strong>{company}</strong>",
                            "detail": tool_input.get("company_domain", "")
                        })
                        # Capture prospect data during tool_call
                        pending_prospect = {
                            "name": company,
                            "domain": tool_input.get("company_domain", ""),
                            "summary": tool_input.get("metadata", {}).get("summary", "") if isinstance(tool_input.get("metadata"), dict) else "",
                            "industry": tool_input.get("metadata", {}).get("industry", "") if isinstance(tool_input.get("metadata"), dict) else "",
                            "fit_reason": tool_input.get("metadata", {}).get("fit_reason", "") if isinstance(tool_input.get("metadata"), dict) else "",
                            "fit_score": tool_input.get("fit_score", 0),
                            "research_complete": True,
                            "email_drafted": False,
                            "discovered_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                        }
                elif tool == "save_contact":
                    if isinstance(tool_input, dict):
                        # Handle both "name" and "first_name/last_name" formats
                        first_name = tool_input.get("first_name", "")
                        last_name = tool_input.get("last_name", "")
                        if first_name or last_name:
                            name = f"{first_name} {last_name}".strip()
                        else:
                            name = tool_input.get("name", "Unknown")
                        title = tool_input.get("title", "")
                        # Get company name - prioritize actual name over ID
                        company = tool_input.get("company_name") or current_prospect_name or "Unknown"
                        if company.startswith("company_") or company.startswith("prospect_"):
                            company = current_prospect_name or company
                        progress_steps.append({
                            "icon": "πŸ‘€",
                            "icon_class": "success",
                            "title": f"Found contact: <strong>{name}</strong>",
                            "detail": f"{title} at {company}"
                        })
                        # Capture contact data during tool_call
                        pending_contact = {
                            "name": name,
                            "title": title or "Unknown",
                            "email": tool_input.get("email", ""),
                            "company": company,
                            "linkedin": tool_input.get("linkedin_url", "")
                        }
                elif tool == "send_email":
                    progress_steps.append({
                        "icon": "βœ‰οΈ",
                        "icon_class": "tool",
                        "title": f'<span class="mcp-tool-badge">MCP</span> send_email',
                        "detail": f"Drafting email for {current_prospect_name or 'prospect'}..."
                    })
                    if isinstance(tool_input, dict):
                        emails_drafted.append({
                            "to": tool_input.get("to", ""),
                            "subject": tool_input.get("subject", ""),
                            "body": tool_input.get("body", ""),
                            "prospect_company": current_prospect_name or tool_input.get("prospect_id", "Unknown"),
                            "created_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                        })
                elif tool == "find_verified_contacts":
                    company = tool_input.get("company_name", "company") if isinstance(tool_input, dict) else "company"
                    progress_steps.append({
                        "icon": "πŸ”Ž",
                        "icon_class": "tool",
                        "title": f'<span class="mcp-tool-badge">MCP</span> find_verified_contacts',
                        "detail": f"Looking for decision makers at {company}..."
                    })

                yield build_accordion(progress_steps)
                progress(progress_pct)

            elif event_type == "tool_result":
                tool = event.get("tool", "")
                result = event.get("result", {})

                if tool == "save_prospect":
                    if pending_prospect:
                        prospects_found.append(pending_prospect)
                        pending_prospect = None

                elif tool == "save_contact":
                    if pending_contact:
                        contacts_found.append(pending_contact)
                        pending_contact = None

                elif tool == "discover_prospects_with_contacts":
                    # Handle the all-in-one prospect discovery tool
                    if isinstance(result, dict):
                        status = result.get("status", "")
                        discovered_prospects = result.get("prospects", [])
                        total_contacts = result.get("contacts_count", 0)
                        companies_checked = result.get("companies_checked", 0)
                        companies_skipped = result.get("companies_skipped", 0)
                        message = result.get("message", "")

                        progress_steps.append({
                            "icon": "πŸ“Š",
                            "icon_class": "success",
                            "title": "<strong>Discovery Complete!</strong>",
                            "detail": f"Checked {companies_checked} companies, found {len(discovered_prospects)} with contacts"
                        })

                        if discovered_prospects:
                            for p in discovered_prospects:
                                # Add to prospects_found with complete data
                                prospect_data = {
                                    "name": p.get("company_name", "Unknown"),
                                    "domain": p.get("domain", ""),
                                    "fit_score": p.get("fit_score", 75),
                                    "summary": p.get("summary", f"Found with {p.get('contact_count', 0)} verified contacts"),
                                    "industry": p.get("industry", "Technology & Services"),
                                    "fit_reason": p.get("fit_reason", "Matches target customer profile based on industry and company size"),
                                    "research_complete": True,
                                    "email_drafted": False,
                                    "discovered_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                                }
                                prospects_found.append(prospect_data)

                                progress_steps.append({
                                    "icon": "βœ…",
                                    "icon_class": "success",
                                    "title": f"<strong>{p.get('company_name')}</strong>",
                                    "detail": f"{p.get('domain')} - {p.get('contact_count', 0)} contacts"
                                })

                                # Add contacts
                                for c in p.get("contacts", []):
                                    contact_data = {
                                        "name": c.get("name", "Unknown"),
                                        "email": c.get("email", ""),
                                        "title": c.get("title", ""),
                                        "company": p.get("company_name", ""),
                                        "verified": True,
                                        "source": c.get("source", "web_search")
                                    }
                                    contacts_found.append(contact_data)
                        else:
                            progress_steps.append({
                                "icon": "⚠️",
                                "icon_class": "warning",
                                "title": "No prospects with verified contacts found",
                                "detail": message
                            })

                        yield build_accordion(progress_steps)

                elif tool == "find_verified_contacts":
                    # Handle verified contacts from the enhanced contact finder (single company)
                    if isinstance(result, dict):
                        status = result.get("status", "")
                        found_contacts = result.get("contacts", [])
                        message = result.get("message", "")

                        if status == "success" and found_contacts:
                            progress_steps.append({
                                "icon": "βœ…",
                                "icon_class": "success",
                                "title": f"Found {len(found_contacts)} verified contacts",
                                "detail": ", ".join([c.get("name", "") for c in found_contacts[:3]])
                            })
                            for c in found_contacts:
                                contact_data = {
                                    "name": c.get("name", "Unknown"),
                                    "email": c.get("email", ""),
                                    "title": c.get("title", ""),
                                    "company": c.get("company", current_prospect_name or ""),
                                    "verified": c.get("verified", True),
                                    "source": c.get("source", "web_search")
                                }
                                contacts_found.append(contact_data)
                        elif status == "no_contacts_found":
                            progress_steps.append({
                                "icon": "⏭️",
                                "icon_class": "warning",
                                "title": "No contacts found",
                                "detail": message
                            })

                        yield build_accordion(progress_steps)

                elif tool == "send_email":
                    progress_steps.append({
                        "icon": "βœ…",
                        "icon_class": "success",
                        "title": "Email drafted",
                        "detail": f"For {current_prospect_name or 'prospect'}"
                    })
                    # Mark prospect as having email drafted
                    if prospects_found:
                        prospects_found[-1]["email_drafted"] = True
                    yield build_accordion(progress_steps)

                elif tool in ["search_web", "search_news"]:
                    count = result.get("count", 0) if isinstance(result, dict) else 0
                    # Update the last progress step with result count
                    if progress_steps and "search" in progress_steps[-1].get("title", "").lower():
                        progress_steps[-1]["detail"] += f" β†’ Found {count} results"
                    # Capture search results to potentially extract prospects from
                    if isinstance(result, dict) and result.get("results"):
                        for r in result.get("results", []):
                            if isinstance(r, dict):
                                title = r.get("title", "")
                                snippet = r.get("body", r.get("text", r.get("snippet", r.get("description", ""))))
                                url = r.get("url", r.get("source", r.get("link", "")))
                                if title:
                                    search_results_for_prospects.append({
                                        "title": title,
                                        "snippet": snippet,
                                        "url": url
                                    })
                    yield build_accordion(progress_steps)

            elif event_type == "thought":
                # Capture AI thoughts/responses as potential final answer
                thought = event.get("thought", "")
                message = event.get("message", "")
                # Filter out HTML/garbage content
                if thought and "CX AI Agent" not in thought and "Powered by AI" not in thought and not thought.startswith("[Processing:"):
                    last_final_answer = thought

            elif event_type == "agent_complete":
                # Auto-generate emails if AI didn't draft any but we have contacts
                if contacts_found and not emails_drafted:
                    progress_steps.append({
                        "icon": "βœ‰οΈ",
                        "icon_class": "tool",
                        "title": "Auto-drafting outreach emails...",
                        "detail": f"Creating personalized emails for {len(contacts_found)} contacts"
                    })
                    yield build_accordion(progress_steps)

                    for c in contacts_found:
                        if c.get("email"):
                            contact_name = c.get("name", "").split()[0] if c.get("name") else "there"
                            full_name = c.get("name", "")
                            company = c.get("company", "your company")
                            title = c.get("title", "")

                            email_body = f"""Hi {contact_name},

I hope this message finds you well. I recently came across {company} and was genuinely impressed by the innovative work your team is doing in the industry.

As {title} at {company}, you're likely focused on driving growth and staying ahead of industry trends. That's exactly why I wanted to reach out.

At {client_name}, we specialize in helping companies like {company} achieve their strategic objectives through tailored solutions. We've helped similar organizations:

β€’ Streamline their operations and reduce costs
β€’ Accelerate growth through innovative strategies
β€’ Stay competitive in an evolving market

I'd love to share some specific insights that have worked well for companies in your space. Would you be open to a brief 15-minute call this week to explore if there might be a fit?

I'm flexible on timing and happy to work around your schedule.

Looking forward to connecting,

Best regards,
{client_name} Team

P.S. If you're not the right person to speak with about this, I'd greatly appreciate it if you could point me in the right direction."""

                            emails_drafted.append({
                                "to": c.get("email"),
                                "subject": f"{contact_name}, quick question about {company}'s 2025 growth plans",
                                "body": email_body,
                                "prospect_company": company,
                                "contact_name": full_name,
                                "created_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                            })

                    progress_steps.append({
                        "icon": "βœ…",
                        "icon_class": "success",
                        "title": f"Drafted {len(emails_drafted)} outreach emails",
                        "detail": "Ready for review in the Emails tab"
                    })
                    yield build_accordion(progress_steps)

                # Save all to knowledge base (with deduplication)
                merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted)

                # Build summary HTML
                summary_html = f'''<div class="progress-summary">
                    <h3>βœ… Discovery Complete!</h3>
                    <table>
                        <tr><td>Prospects Found</td><td><strong>{len(prospects_found)}</strong></td></tr>
                        <tr><td>Decision Makers</td><td><strong>{len(contacts_found)}</strong></td></tr>
                        <tr><td>Emails Drafted</td><td><strong>{len(emails_drafted)}</strong></td></tr>
                    </table>
                </div>'''

                # Build detailed results section with collapsible prospect cards
                results_html = ""
                if prospects_found or contacts_found or emails_drafted:
                    results_html += """<div style="margin-top: 20px;">
                        <h3 style="color: var(--text-primary); margin-bottom: 16px;">🎯 Discovered Prospects</h3>"""

                    for p in prospects_found:
                        p_name = p.get('name', 'Unknown')
                        p_name_lower = p_name.lower()

                        # Find contacts for this prospect - strict matching by exact company name
                        p_domain = p.get('domain', '').lower().replace('www.', '')
                        p_contacts = []
                        for c in contacts_found:
                            c_company = c.get("company", "").lower()
                            c_email = c.get("email", "").lower()
                            # Match by exact company name OR by email domain
                            if (c_company == p_name_lower or
                                p_name_lower == c_company or
                                (p_domain and p_domain in c_email)):
                                p_contacts.append(c)

                        # Find emails for this prospect - strict matching
                        p_emails = []
                        for e in emails_drafted:
                            e_company = e.get("prospect_company", "").lower()
                            e_to = e.get("to", "").lower()
                            if (e_company == p_name_lower or
                                p_name_lower == e_company or
                                (p_domain and p_domain in e_to)):
                                p_emails.append(e)

                        # Build contacts HTML
                        contacts_section = ""
                        if p_contacts:
                            contacts_section = "<div style='margin-top: 12px;'><strong style='color: var(--text-primary);'>πŸ‘₯ Decision Makers:</strong><ul style='margin: 8px 0 0 0; padding-left: 20px;'>"
                            for c in p_contacts:
                                contacts_section += f"<li><strong>{c.get('name', 'Unknown')}</strong> - {c.get('title', 'Unknown')}"
                                if c.get('email'):
                                    contacts_section += f" <span style='color: var(--primary-blue);'>({c.get('email')})</span>"
                                contacts_section += "</li>"
                            contacts_section += "</ul></div>"

                        # Build emails HTML with collapsible section
                        emails_section = ""
                        if p_emails:
                            emails_section = "<div style='margin-top: 12px;'><details style='background: var(--bg-secondary); border-radius: 8px; padding: 0;'>"
                            emails_section += f"<summary style='padding: 10px 14px; cursor: pointer; font-weight: 600; color: var(--primary-blue);'>βœ‰οΈ View Outreach Email ({len(p_emails)})</summary>"
                            emails_section += "<div style='padding: 12px 14px; border-top: 1px solid var(--border-color);'>"
                            for e in p_emails:
                                email_body = e.get('body', '').replace('\n', '<br>')
                                emails_section += f"""
                                    <div style='margin-bottom: 12px;'>
                                        <div style='font-size: 12px; color: #666;'><strong>To:</strong> {e.get('to', 'Unknown')}</div>
                                        <div style='font-size: 13px; font-weight: 600; color: #333; margin: 6px 0;'><strong>Subject:</strong> {e.get('subject', 'No subject')}</div>
                                        <div style='font-size: 13px; color: #333; line-height: 1.6; background: #f8f9fa; padding: 14px; border-radius: 6px; border: 1px solid #dee2e6;'>{email_body}</div>
                                    </div>"""
                            emails_section += "</div></details></div>"

                        results_html += f"""
                        <details class="prospect-card" style="margin-bottom: 12px;" open>
                            <summary class="prospect-card-header" style="padding: 14px 18px;">
                                <span class="prospect-card-title">🏒 {p_name}</span>
                                <span class="prospect-card-badge badge-researched">{'βœ‰οΈ EMAIL READY' if p_emails else 'βœ… DISCOVERED'}</span>
                            </summary>
                            <div class="prospect-card-details" style="padding: 16px 18px;">
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;">
                                    <div><strong style="color: var(--text-secondary); font-size: 12px;">🏭 INDUSTRY</strong><div style="color: var(--text-primary);">{p.get('industry', 'Technology & Services')}</div></div>
                                    <div><strong style="color: var(--text-secondary); font-size: 12px;">🌐 DOMAIN</strong><div style="color: var(--text-primary);">{p.get('domain', 'N/A')}</div></div>
                                </div>
                                <div style="margin-bottom: 12px;"><strong style="color: var(--text-secondary); font-size: 12px;">πŸ“‹ SUMMARY</strong><div style="color: var(--text-primary); font-size: 13px; margin-top: 4px;">{p.get('summary', 'No summary available')}</div></div>
                                <div style="margin-bottom: 12px;"><strong style="color: var(--text-secondary); font-size: 12px;">🎯 FIT REASON</strong><div style="color: var(--text-primary); font-size: 13px; margin-top: 4px;">{p.get('fit_reason', 'Matches target customer profile')}</div></div>
                                {contacts_section}
                                {emails_section}
                            </div>
                        </details>"""

                    results_html += "</div>"
                elif not prospects_found:
                    results_html = """<div style="margin-top: 20px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px; padding: 14px;">
                        <strong>ℹ️ Note:</strong> No prospects were saved by the AI. Try running discovery again or adjusting your search criteria.
                    </div>"""

                # Yield final accordion with summary and results
                yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html + results_html)
                progress(1.0)
                return

            elif event_type == "agent_max_iterations":
                # Auto-generate emails if we have contacts but no emails
                if contacts_found and not emails_drafted:
                    for c in contacts_found:
                        if c.get("email"):
                            contact_name = c.get("name", "").split()[0] if c.get("name") else "there"
                            full_name = c.get("name", "")
                            company = c.get("company", "your company")
                            title = c.get("title", "")
                            email_body = f"""Hi {contact_name},

I hope this message finds you well. I recently came across {company} and was genuinely impressed by the innovative work your team is doing.

As {title} at {company}, you're likely focused on driving growth and staying ahead of industry trends. That's exactly why I wanted to reach out.

At {client_name}, we specialize in helping companies like {company} achieve their strategic objectives. We've helped similar organizations:

β€’ Streamline their operations and reduce costs
β€’ Accelerate growth through innovative strategies
β€’ Stay competitive in an evolving market

Would you be open to a brief 15-minute call this week to explore if there might be a fit?

Best regards,
{client_name} Team"""
                            emails_drafted.append({
                                "to": c.get("email"),
                                "subject": f"{contact_name}, quick question about {company}'s 2025 growth plans",
                                "body": email_body,
                                "prospect_company": company,
                                "contact_name": full_name,
                                "created_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                            })

                # Save what we found so far (with deduplication)
                merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted)

                progress_steps.append({
                    "icon": "⏱️",
                    "icon_class": "warning",
                    "title": "Max iterations reached",
                    "detail": "Discovery stopped but results saved"
                })

                summary_html = f'''<div class="progress-summary" style="background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);">
                    <h3>⏱️ Discovery Summary (Partial)</h3>
                    <table>
                        <tr><td>Prospects Found</td><td><strong>{len(prospects_found)}</strong></td></tr>
                        <tr><td>Decision Makers</td><td><strong>{len(contacts_found)}</strong></td></tr>
                        <tr><td>Emails Drafted</td><td><strong>{len(emails_drafted)}</strong></td></tr>
                    </table>
                </div>'''
                yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html)
                return

            elif event_type == "agent_error":
                # Save what we found so far even on error (with deduplication)
                merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted)

                error_msg = event.get("error", "Unknown error")
                progress_steps.append({
                    "icon": "❌",
                    "icon_class": "error",
                    "title": "Error occurred",
                    "detail": str(error_msg)[:100]
                })

                summary_html = f'''<div class="progress-summary" style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);">
                    <h3>⚠️ Discovery Interrupted</h3>
                    <table>
                        <tr><td>Prospects Found</td><td><strong>{len(prospects_found)}</strong></td></tr>
                        <tr><td>Decision Makers</td><td><strong>{len(contacts_found)}</strong></td></tr>
                        <tr><td>Emails Drafted</td><td><strong>{len(emails_drafted)}</strong></td></tr>
                    </table>
                </div>'''
                yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html)
                return

    except Exception as e:
        logger.error(f"Discovery error: {e}")
        # Save what we found (with deduplication)
        merge_to_knowledge_base(prospects_found, contacts_found, emails_drafted)

        progress_steps.append({
            "icon": "❌",
            "icon_class": "error",
            "title": "Discovery interrupted",
            "detail": str(e)[:100]
        })

        summary_html = f'''<div class="progress-summary" style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);">
            <h3>⚠️ Discovery Error</h3>
            <p>Saved {len(prospects_found)} prospects found so far.</p>
        </div>'''
        yield build_accordion(progress_steps, is_loading=False, summary_html=summary_html)


# ============================================================================
# AI CHAT - With MCP Tool Support
# ============================================================================
async def chat_with_ai_async(message: str, history: list, hf_token: str):
    """AI Chat powered by LLM with full MCP tool support"""
    if not knowledge_base["client"]["name"]:
        yield history + [[message, "⚠️ Please complete Setup first. Enter your company name in the Setup tab."]], ""
        return

    if not message.strip():
        yield history, ""
        return

    token = get_hf_token(hf_token)
    if not token:
        yield history + [[message, "⚠️ Please enter your HuggingFace token in the Setup tab."]], ""
        return

    client_name = knowledge_base["client"]["name"]
    client_info = knowledge_base["client"].get("raw_research", "")

    # Always use LLM for all queries - this is a full AI assistant
    try:
        agent = AutonomousMCPAgentHF(
            mcp_registry=mcp_registry,
            hf_token=token,
            provider=HF_PROVIDER,
            model=HF_MODEL
        )

        # Build comprehensive context with all knowledge base data
        prospects_detail = ""
        if knowledge_base["prospects"]:
            for i, p in enumerate(knowledge_base["prospects"][:10], 1):
                p_name = p.get('name', 'Unknown')
                p_name_lower = p_name.lower()
                # Get contacts for this prospect
                p_contacts = [c for c in knowledge_base["contacts"]
                             if p_name_lower in c.get("company", "").lower()
                             or c.get("company", "").lower() in p_name_lower]
                contacts_str = ", ".join([f"{c.get('name')} ({c.get('email')})" for c in p_contacts]) if p_contacts else "No contacts"
                prospects_detail += f"{i}. {p_name} - {p.get('industry', 'Unknown industry')}, Fit: {p.get('fit_score', 'N/A')}\n"
                prospects_detail += f"   Summary: {p.get('summary', 'No summary')[:100]}\n"
                prospects_detail += f"   Contacts: {contacts_str}\n"
        else:
            prospects_detail = "No prospects discovered yet."

        emails_detail = ""
        if knowledge_base["emails"]:
            for e in knowledge_base["emails"][:5]:
                emails_detail += f"- To: {e.get('to')} | Subject: {e.get('subject', 'No subject')[:50]}\n"
        else:
            emails_detail = "No emails drafted yet."

        task = f"""You are an AI sales assistant for {client_name}. You are a helpful, knowledgeable assistant that can answer any question about the sales pipeline, prospects, contacts, and help with various sales tasks.

ABOUT {client_name}:
{client_info[:500] if client_info else "No company research available yet."}

CURRENT SALES PIPELINE:
======================
PROSPECTS ({len(knowledge_base['prospects'])}):
{prospects_detail}

CONTACTS ({len(knowledge_base['contacts'])}):
{len(knowledge_base['contacts'])} decision makers found across prospects.

DRAFTED EMAILS ({len(knowledge_base['emails'])}):
{emails_detail}

USER MESSAGE: {message}

INSTRUCTIONS:
- Answer the user's question helpfully and completely
- If they ask about prospects, contacts, or emails, use the data above
- If they ask you to search for something, use search_web tool
- If they ask you to draft an email, create a professional, personalized email
- If they ask for talking points, strategies, or recommendations, provide thoughtful, specific advice
- If they ask to find similar companies or new prospects, use search_web to research
- Be conversational and helpful - you're a knowledgeable sales assistant
- Don't say "I don't have that capability" - try to help with whatever they ask
- For follow-up questions, use context from the conversation

Respond naturally and helpfully to the user's message."""

        response_text = ""
        current_history = history + [[message, "πŸ€– Thinking..."]]
        yield current_history, ""

        async for event in agent.run(task, max_iterations=12):
            event_type = event.get("type")

            if event_type == "tool_call":
                tool = event.get("tool", "")
                tool_input = event.get("input", {})
                if tool == "search_web":
                    query = tool_input.get("query", "") if isinstance(tool_input, dict) else ""
                    response_text += f"πŸ” Searching: {query[:50]}...\n"
                elif tool == "send_email":
                    response_text += f"βœ‰οΈ Drafting email...\n"
                else:
                    response_text += f"πŸ”§ Using {tool}...\n"
                current_history = history + [[message, response_text]]
                yield current_history, ""

            elif event_type == "tool_result":
                tool = event.get("tool", "")
                result = event.get("result", {})

                # Capture data from tool results (with deduplication)
                if tool == "save_prospect" and isinstance(result, dict):
                    prospect_data = {
                        "name": result.get("company_name", result.get("prospect_id", "Unknown")),
                        "domain": result.get("company_domain", result.get("domain", "")),
                        "fit_score": result.get("fit_score", 75),
                        "research_complete": True,
                        "discovered_at": datetime.now().strftime("%Y-%m-%d %H:%M")
                    }
                    merge_to_knowledge_base([prospect_data], [], [])
                    response_text += f"βœ… Saved prospect: {prospect_data['name']}\n"

                elif tool == "save_contact" and isinstance(result, dict):
                    merge_to_knowledge_base([], [result], [])
                    response_text += f"βœ… Saved contact\n"

                elif tool == "send_email" and isinstance(result, dict):
                    merge_to_knowledge_base([], [], [result])
                    response_text += f"βœ… Email drafted\n"

                elif tool == "search_web":
                    count = result.get("count", 0) if isinstance(result, dict) else 0
                    response_text += f"βœ… Found {count} results\n"

                current_history = history + [[message, response_text]]
                yield current_history, ""

            elif event_type == "thought":
                thought = event.get("thought", "")
                # Only show substantive thoughts, not processing messages
                if thought and len(thought) > 50 and not thought.startswith("[Processing"):
                    # This is likely the AI's actual response
                    pass  # We'll get this in agent_complete

            elif event_type == "agent_complete":
                final = event.get("final_answer", "")
                if final and "CX AI Agent" not in final and "Powered by AI" not in final:
                    # Clean response - show just the final answer
                    if response_text:
                        response_text += "\n---\n\n"
                    response_text += final
                elif not response_text:
                    response_text = "I've processed your request. Is there anything else you'd like to know?"
                current_history = history + [[message, response_text]]
                yield current_history, ""
                return

            elif event_type == "agent_error":
                error = event.get("error", "Unknown error")
                if "rate limit" in str(error).lower():
                    response_text += "\n⚠️ Rate limit reached. Please wait a moment and try again."
                else:
                    response_text += f"\n⚠️ Error: {error}"
                current_history = history + [[message, response_text]]
                yield current_history, ""
                return

            elif event_type == "agent_max_iterations":
                if not response_text:
                    response_text = "I'm still processing your request. The task may be complex - please try a simpler question or try again."
                current_history = history + [[message, response_text]]
                yield current_history, ""
                return

        # If we get here without returning
        if not response_text:
            response_text = "I processed your request. Let me know if you need anything else!"
        yield history + [[message, response_text]], ""

    except Exception as e:
        logger.error(f"Chat agent error: {e}")
        error_msg = str(e)
        if "rate limit" in error_msg.lower() or "429" in error_msg:
            yield history + [[message, "⚠️ Rate limit reached. Please wait a moment and try again."]], ""
        else:
            yield history + [[message, f"⚠️ Error: {error_msg}"]], ""


def chat_with_ai(message: str, history: list) -> tuple:
    """Chat function - handles queries using local data and templates"""
    if not knowledge_base["client"]["name"]:
        return history + [[message, "⚠️ Please complete Setup first. Enter your HuggingFace token and company name."]], ""

    if not session_hf_token.get("token"):
        return history + [[message, "⚠️ Please enter your HuggingFace token in the **Setup** tab first."]], ""

    if not message.strip():
        return history, ""

    client_name = knowledge_base["client"]["name"]
    msg_lower = message.lower()

    def find_prospect_by_name(query: str):
        """Find prospect by exact or partial name match"""
        query_lower = query.lower()
        # First try exact match
        for p in knowledge_base["prospects"]:
            if p.get("name", "").lower() == query_lower:
                return p
        # Then try if prospect name contains query
        for p in knowledge_base["prospects"]:
            if query_lower in p.get("name", "").lower():
                return p
        # Then try if query contains prospect name
        for p in knowledge_base["prospects"]:
            p_name = p.get("name", "").lower()
            if p_name in query_lower:
                return p
        # Finally try partial word match
        query_words = set(query_lower.split())
        for p in knowledge_base["prospects"]:
            p_words = set(p.get("name", "").lower().split())
            if query_words & p_words:  # Any word in common
                return p
        return None

    # Check for specific prospect mention using improved matching
    mentioned_prospect = find_prospect_by_name(message)

    # Handle "find decision makers" / "find contacts" for a known prospect
    if any(kw in msg_lower for kw in ["find decision", "find contact", "who works at", "contacts at"]):
        if mentioned_prospect:
            p_name = mentioned_prospect["name"]
            p_name_lower = p_name.lower()
            contacts = [c for c in knowledge_base["contacts"]
                       if p_name_lower in c.get("company", "").lower()
                       or c.get("company", "").lower() in p_name_lower]

            if contacts:
                response = f"## πŸ‘₯ Decision Makers at {p_name}\n\n"
                for c in contacts:
                    response += f"**{c.get('name', 'Unknown')}** - {c.get('title', 'Unknown')}\n"
                    response += f"   - Email: {c.get('email', 'Not available')}\n"
                    response += f"   - Company: {c.get('company', p_name)}\n\n"
            else:
                response = f"No contacts found yet for **{p_name}**.\n\n"
                response += "To find contacts, go to **Prospects Tab** and run **Find Prospects** again."
            return history + [[message, response]], ""

    # Handle "show email" - just viewing existing drafts
    if any(kw in msg_lower for kw in ["show email", "existing email", "what email", "see email", "view email"]):
        if mentioned_prospect:
            p_name = mentioned_prospect["name"]
            p_name_lower = p_name.lower()
            existing_emails = [e for e in knowledge_base["emails"]
                              if p_name_lower in e.get("prospect_company", "").lower()]
            if existing_emails:
                email = existing_emails[0]
                response = f"## βœ‰οΈ Existing Email Draft for {p_name}\n\n"
                response += f"**To:** {email.get('to', 'N/A')}\n"
                response += f"**Subject:** {email.get('subject', 'N/A')}\n\n"
                response += f"---\n\n{email.get('body', 'No content')}\n\n"
                response += "---\n\n*This email was drafted during prospect discovery.*"
            else:
                response = f"No existing email drafts found for **{p_name}**."
            return history + [[message, response]], ""

    # Handle "draft/write/compose email" - create custom email based on user's request
    if any(kw in msg_lower for kw in ["draft", "write", "compose", "create email", "email to", "send email", "mail to"]):
        if mentioned_prospect:
            p_name = mentioned_prospect["name"]
            p_name_lower = p_name.lower()

            # Get contact info
            contacts = [c for c in knowledge_base["contacts"]
                       if p_name_lower in c.get("company", "").lower()
                       or c.get("company", "").lower() in p_name_lower]
            contact = contacts[0] if contacts else None
            to_email = contact.get("email", f"contact@{p_name.lower().replace(' ', '')}.com") if contact else f"contact@{p_name.lower().replace(' ', '')}.com"
            contact_name = contact.get("name", "").split()[0] if contact and contact.get("name") else "there"
            contact_title = contact.get("title", "") if contact else ""

            # Extract specific details from user's message
            import re

            # Check if this is a meeting request
            is_meeting_request = any(kw in msg_lower for kw in ["meeting", "call", "demo", "schedule", "appointment"])

            # Extract date/time info
            date_match = re.search(r'(\d{1,2}(?:st|nd|rd|th)?\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{4}|\w+day(?:\s+next\s+week)?|\d{1,2}[/-]\d{1,2}[/-]\d{2,4})', msg_lower)
            time_match = re.search(r'(\d{1,2}:\d{2}|\d{1,2}\s*(?:am|pm))', msg_lower)
            duration_match = re.search(r'(\d+)\s*(?:min|minute|hour)', msg_lower)

            date_str = date_match.group(1).title() if date_match else ""
            time_str = time_match.group(1) if time_match else ""
            duration_str = duration_match.group(0) if duration_match else ""

            # Extract the purpose/topic from the message
            # Remove common words to find the custom content
            custom_content = message
            for word in ["draft", "write", "compose", "email", "mail", "to", p_name.lower(), "asking", "that", "can", "we", "a", "an", "the", "for", "about"]:
                custom_content = re.sub(rf'\b{word}\b', '', custom_content, flags=re.IGNORECASE)
            custom_content = ' '.join(custom_content.split()).strip()

            # Generate custom email based on context
            response = f"## βœ‰οΈ Custom Email Draft for {p_name}\n\n"
            response += f"**To:** {to_email}\n"

            if is_meeting_request:
                # Meeting request email
                subject = f"Meeting Request: {client_name} x {p_name}"
                if date_str:
                    subject = f"Meeting Request for {date_str} - {client_name} x {p_name}"
                response += f"**Subject:** {subject}\n\n"
                response += f"---\n\n"
                response += f"Dear {contact_name},\n\n"
                response += f"I hope this email finds you well.\n\n"
                response += f"I'm reaching out from {client_name} regarding a potential collaboration with {p_name}. "
                response += f"Based on our research, we believe there's a strong synergy between our companies, "
                response += f"particularly in the {mentioned_prospect.get('industry', 'your industry')} space.\n\n"

                if date_str or time_str or duration_str:
                    response += f"I would like to propose a meeting"
                    if date_str:
                        response += f" on **{date_str}**"
                    if time_str:
                        response += f" at **{time_str}**"
                    if duration_str:
                        response += f" for **{duration_str}**"
                    response += f" to discuss how {client_name} can help {p_name} achieve its goals.\n\n"
                else:
                    response += f"Would you be available for a brief call this week to discuss how {client_name} can support {p_name}'s growth?\n\n"

                response += f"During our conversation, I'd love to explore:\n"
                response += f"- How {client_name}'s solutions align with {p_name}'s current initiatives\n"
                response += f"- Specific ways we can add value to your {mentioned_prospect.get('industry', 'business')}\n"
                response += f"- Next steps for a potential partnership\n\n"
                response += f"Please let me know if this time works for you, or suggest an alternative that fits your schedule.\n\n"
            else:
                # General outreach with custom content
                subject = f"{client_name} + {p_name}: Let's Connect"
                response += f"**Subject:** {subject}\n\n"
                response += f"---\n\n"
                response += f"Dear {contact_name},\n\n"
                response += f"I'm reaching out from {client_name} regarding {p_name}.\n\n"
                if custom_content:
                    response += f"{custom_content}\n\n"
                response += f"Based on our research into {p_name}'s work in {mentioned_prospect.get('industry', 'your industry')}, "
                response += f"we believe {client_name} can provide significant value.\n\n"
                response += f"**About {p_name}:** {mentioned_prospect.get('summary', '')}\n\n"
                response += f"**Why we're reaching out:** {mentioned_prospect.get('fit_reason', 'We see great potential for collaboration.')}\n\n"
                response += f"Would you be open to a conversation about how we can work together?\n\n"

            response += f"Best regards,\n"
            response += f"[Your Name]\n"
            response += f"{client_name}\n\n"
            response += f"---\n\n"
            response += f"*πŸ“ This is a custom draft based on your request. Edit as needed before sending.*"

            return history + [[message, response]], ""

    # Handle "suggest talking points" for a prospect
    if any(kw in msg_lower for kw in ["talking point", "suggest", "recommend", "strategy"]):
        if mentioned_prospect:
            p_name = mentioned_prospect["name"]
            response = f"## πŸ’‘ Talking Points for {p_name}\n\n"
            response += f"**About {p_name}:**\n"
            response += f"- Industry: {mentioned_prospect.get('industry', 'Unknown')}\n"
            response += f"- {mentioned_prospect.get('summary', 'No summary available')}\n\n"
            response += f"**Why they're a fit for {client_name}:**\n"
            response += f"- {mentioned_prospect.get('fit_reason', 'Matches target customer profile')}\n\n"
            response += f"**Suggested talking points:**\n"
            response += f"1. Reference their focus on {mentioned_prospect.get('industry', 'their industry')}\n"
            response += f"2. Highlight how {client_name} can help with scalability\n"
            response += f"3. Mention success stories from similar companies\n"
            response += f"4. Propose a specific next step (demo, call, pilot)\n"
            return history + [[message, response]], ""

    # Handle "research [prospect]" or "analyze [prospect]" - show detailed info
    if any(kw in msg_lower for kw in ["research", "analyze", "details about", "info on", "information about"]):
        if mentioned_prospect:
            p_name = mentioned_prospect["name"]
            p_name_lower = p_name.lower()

            # Get contacts and emails for this prospect
            contacts = [c for c in knowledge_base["contacts"]
                       if p_name_lower in c.get("company", "").lower()
                       or c.get("company", "").lower() in p_name_lower]
            emails = [e for e in knowledge_base["emails"]
                     if p_name_lower in e.get("prospect_company", "").lower()]

            response = f"## πŸ” Research: {p_name}\n\n"
            response += f"### Company Overview\n"
            response += f"- **Industry:** {mentioned_prospect.get('industry', 'Unknown')}\n"
            response += f"- **Fit Score:** {mentioned_prospect.get('fit_score', 'N/A')}/100\n"
            response += f"- **Summary:** {mentioned_prospect.get('summary', 'No summary available')}\n\n"

            response += f"### Why They're a Good Fit for {client_name}\n"
            response += f"{mentioned_prospect.get('fit_reason', 'Matches target customer profile')}\n\n"

            response += f"### Decision Makers ({len(contacts)})\n"
            if contacts:
                for c in contacts:
                    response += f"- **{c.get('name', 'Unknown')}** - {c.get('title', 'Unknown')}\n"
                    response += f"  - Email: {c.get('email', 'N/A')}\n"
            else:
                response += "No contacts found yet.\n"

            response += f"\n### Outreach Status\n"
            if emails:
                response += f"βœ… {len(emails)} email(s) drafted\n"
                for e in emails:
                    response += f"- To: {e.get('to', 'N/A')} - \"{e.get('subject', 'No subject')[:40]}...\"\n"
            else:
                response += "⏳ No emails drafted yet\n"

            return history + [[message, response]], ""

    # Handle "find competitors" or "competitors to"
    if any(kw in msg_lower for kw in ["competitor", "similar to", "like "]):
        if mentioned_prospect:
            p_name = mentioned_prospect["name"]
            industry = mentioned_prospect.get('industry', 'Unknown')
            response = f"## 🏒 Finding Similar Companies to {p_name}\n\n"
            response += f"**{p_name}** is in the **{industry}** industry.\n\n"
            response += f"To find more companies similar to {p_name}:\n\n"
            response += f"1. Go to **Prospects Tab**\n"
            response += f"2. The AI will search for companies in {industry}\n"
            response += f"3. It will identify competitors and similar businesses\n\n"
            response += f"**Currently in your pipeline:**\n"
            other_in_industry = [p for p in knowledge_base["prospects"]
                                if p.get("industry", "").lower() == industry.lower() and p.get("name") != p_name]
            if other_in_industry:
                response += f"Other {industry} prospects:\n"
                for p in other_in_industry:
                    response += f"- {p.get('name')} (Fit: {p.get('fit_score', 'N/A')})\n"
            else:
                response += f"No other {industry} prospects found yet.\n"
            return history + [[message, response]], ""

    # For generic "search for new" or "discover new" - guide to prospects tab
    if any(kw in msg_lower for kw in ["search for new", "find new", "discover new", "look for new"]):
        response = f"""πŸ” **Search for New Prospects**

To discover new companies, use the **Prospects Tab**:

1. Go to **Prospects** tab
2. Enter the number of prospects to find
3. Click **"Find Prospects & Contacts"**

The AI will:
- Search for companies matching {client_name}'s target market
- Find decision makers at each company
- Draft personalized outreach emails

**Currently in your pipeline:**
- Prospects: {len(knowledge_base['prospects'])}
- Contacts: {len(knowledge_base['contacts'])}
- Emails: {len(knowledge_base['emails'])}
"""
        return history + [[message, response]], ""

    # For simple queries, use local knowledge base lookup
    response = get_local_response(message, client_name)
    return history + [[message, response]], ""


def get_local_response(message: str, client_name: str) -> str:
    """Handle simple queries locally without AI agent"""
    msg_lower = message.lower()

    # Detect user intent and respond accordingly
    response = ""

    # Intent: List prospects
    if any(kw in msg_lower for kw in ["list prospect", "show prospect", "all prospect", "prospects"]):
        if knowledge_base["prospects"]:
            response = f"## 🎯 Prospects for {client_name}\n\n"
            for i, p in enumerate(knowledge_base["prospects"], 1):
                response += f"**{i}. {p.get('name', 'Unknown')}**\n"
                response += f"   - Industry: {p.get('industry', 'Unknown')}\n"
                response += f"   - Fit Score: {p.get('fit_score', 'N/A')}/100\n"
                if p.get('summary'):
                    response += f"   - Summary: {p.get('summary', '')[:150]}...\n" if len(p.get('summary', '')) > 150 else f"   - Summary: {p.get('summary', '')}\n"
                response += "\n"
        else:
            response = "No prospects discovered yet. Go to the **Discovery** tab and click **Find Prospects & Contacts** to discover potential customers."

    # Intent: List contacts / decision makers
    elif any(kw in msg_lower for kw in ["contact", "decision maker", "who", "email address", "reach"]):
        # Check if asking about specific prospect
        specific_prospect = None
        for p in knowledge_base["prospects"]:
            if p.get("name", "").lower() in msg_lower:
                specific_prospect = p
                break

        if specific_prospect:
            prospect_contacts = [c for c in knowledge_base["contacts"] if c.get("company", "").lower() == specific_prospect["name"].lower()]
            if prospect_contacts:
                response = f"## πŸ‘₯ Decision Makers at {specific_prospect['name']}\n\n"
                for c in prospect_contacts:
                    response += f"**{c.get('name', 'Unknown')}**\n"
                    response += f"   - Title: {c.get('title', 'Unknown')}\n"
                    response += f"   - Email: {c.get('email', 'Not available')}\n"
                    if c.get('linkedin'):
                        response += f"   - LinkedIn: {c.get('linkedin')}\n"
                    response += "\n"
            else:
                response = f"No contacts found for **{specific_prospect['name']}** yet."
        elif knowledge_base["contacts"]:
            response = f"## πŸ‘₯ All Decision Makers\n\n"
            for c in knowledge_base["contacts"]:
                response += f"**{c.get('name', 'Unknown')}** - {c.get('title', 'Unknown')}\n"
                response += f"   - Company: {c.get('company', 'Unknown')}\n"
                response += f"   - Email: {c.get('email', 'Not available')}\n\n"
        else:
            response = "No contacts discovered yet. Run **Find Prospects** to discover decision makers."

    # Intent: Show emails
    elif any(kw in msg_lower for kw in ["email", "draft", "outreach", "message"]):
        specific_prospect = None
        for p in knowledge_base["prospects"]:
            if p.get("name", "").lower() in msg_lower:
                specific_prospect = p
                break

        if specific_prospect:
            prospect_emails = [e for e in knowledge_base["emails"] if specific_prospect["name"].lower() in e.get("prospect_company", "").lower()]
            if prospect_emails:
                response = f"## βœ‰οΈ Emails for {specific_prospect['name']}\n\n"
                for e in prospect_emails:
                    response += f"**To:** {e.get('to', 'Unknown')}\n"
                    response += f"**Subject:** {e.get('subject', 'No subject')}\n\n"
                    response += f"```\n{e.get('body', 'No content')}\n```\n\n"
            else:
                response = f"No emails drafted for **{specific_prospect['name']}** yet."
        elif knowledge_base["emails"]:
            response = "## βœ‰οΈ All Drafted Emails\n\n"
            for e in knowledge_base["emails"]:
                response += f"**To:** {e.get('to', 'Unknown')} ({e.get('prospect_company', 'Unknown')})\n"
                response += f"**Subject:** {e.get('subject', 'No subject')}\n\n"
        else:
            response = "No emails drafted yet. Run **Find Prospects** to have AI draft outreach emails."

    # Intent: Tell me about / describe prospect
    elif any(kw in msg_lower for kw in ["tell me about", "describe", "info about", "details", "about"]):
        specific_prospect = None
        for p in knowledge_base["prospects"]:
            if p.get("name", "").lower() in msg_lower:
                specific_prospect = p
                break

        if specific_prospect:
            response = f"## 🏒 {specific_prospect['name']}\n\n"
            response += f"**Industry:** {specific_prospect.get('industry', 'Unknown')}\n"
            response += f"**Fit Score:** {specific_prospect.get('fit_score', 'N/A')}/100\n\n"
            if specific_prospect.get('summary'):
                response += f"**Summary:**\n{specific_prospect.get('summary')}\n\n"
            if specific_prospect.get('fit_reason'):
                response += f"**Why they're a good fit:**\n{specific_prospect.get('fit_reason')}\n\n"

            # Show contacts for this prospect
            prospect_contacts = [c for c in knowledge_base["contacts"] if c.get("company", "").lower() == specific_prospect["name"].lower()]
            if prospect_contacts:
                response += f"**Decision Makers ({len(prospect_contacts)}):**\n"
                for c in prospect_contacts:
                    response += f"- {c.get('name', 'Unknown')} - {c.get('title', '')} ({c.get('email', 'no email')})\n"
        elif knowledge_base["prospects"]:
            response = "Which prospect would you like to know about?\n\n**Available prospects:**\n"
            for p in knowledge_base["prospects"]:
                response += f"- {p.get('name', 'Unknown')}\n"
        else:
            response = "No prospects discovered yet. Run **Find Prospects** first."

    # Intent: Summary / overview
    elif any(kw in msg_lower for kw in ["summary", "overview", "status", "pipeline", "how many"]):
        response = f"## πŸ“Š {client_name} Sales Pipeline Summary\n\n"
        response += f"| Metric | Count |\n"
        response += f"|--------|-------|\n"
        response += f"| Prospects | {len(knowledge_base['prospects'])} |\n"
        response += f"| Decision Makers | {len(knowledge_base['contacts'])} |\n"
        response += f"| Emails Drafted | {len(knowledge_base['emails'])} |\n\n"

        if knowledge_base["prospects"]:
            response += "**Prospects:**\n"
            for p in knowledge_base["prospects"]:
                response += f"- {p.get('name', 'Unknown')} (Fit: {p.get('fit_score', 'N/A')})\n"

    # Intent: Help / what can you do
    elif any(kw in msg_lower for kw in ["help", "what can", "how do", "?"]):
        response = f"""## πŸ’¬ {client_name} Sales Assistant

I can help you with information about your sales pipeline. Try asking:

**About Prospects:**
- "List all prospects"
- "Tell me about [prospect name]"
- "Show prospect details"

**About Contacts:**
- "Who are the decision makers?"
- "Show contacts for [prospect name]"
- "List all contacts"

**About Emails:**
- "Show drafted emails"
- "What emails do we have for [prospect name]?"

**Pipeline Overview:**
- "Give me a summary"
- "How many prospects do we have?"
- "Pipeline status"
"""

    # Default: Try to be helpful
    else:
        prospects_list = ", ".join([p.get("name", "Unknown") for p in knowledge_base["prospects"]]) if knowledge_base["prospects"] else "None yet"
        response = f"""I'm not sure what you're asking. Here's what I know:

**Current Pipeline:**
- Prospects: {len(knowledge_base["prospects"])} ({prospects_list})
- Contacts: {len(knowledge_base["contacts"])}
- Emails: {len(knowledge_base["emails"])}

Try asking:
- "List prospects"
- "Tell me about [prospect name]"
- "Show contacts"
- "Show emails"
- "Give me a summary"
"""

    return response


# ============================================================================
# HANDOFF PACKET
# ============================================================================
def generate_handoff_packet(prospect_name: str) -> str:
    if not prospect_name:
        return "⚠️ Please select a prospect."

    prospect = next((p for p in knowledge_base["prospects"] if p["name"] == prospect_name), None)
    if not prospect:
        return f"⚠️ Prospect '{prospect_name}' not found."

    # Case-insensitive contact matching with partial match support
    prospect_name_lower = prospect_name.lower()
    contacts = [c for c in knowledge_base["contacts"]
                if prospect_name_lower in c.get("company", "").lower()
                or c.get("company", "").lower() in prospect_name_lower]

    # Also match emails for this prospect (case-insensitive, partial match)
    emails_for_prospect = [e for e in knowledge_base["emails"]
                          if prospect_name_lower in e.get("prospect_company", "").lower()
                          or e.get("prospect_company", "").lower() in prospect_name_lower]
    email = emails_for_prospect[0] if emails_for_prospect else None

    # If no contacts found but we have an email, extract contact from email
    if not contacts and email:
        email_to = email.get("to", "")
        if email_to:
            # Try to extract name from email body or use email
            email_body = email.get("body", "")
            # Look for "Dear [Name]" pattern
            import re
            name_match = re.search(r'Dear\s+([A-Z][a-z]+)', email_body)
            contact_name = name_match.group(1) if name_match else email_to.split('@')[0].title()
            contacts = [{
                "name": contact_name,
                "email": email_to,
                "title": "Contact",
                "company": prospect_name
            }]

    client_name = knowledge_base["client"]["name"]

    packet = f"""# πŸ“‹ Sales Handoff Packet

## {prospect["name"]}

**Prepared for:** {client_name}
**Date:** {datetime.now().strftime("%Y-%m-%d")}

---

## 1. Company Overview

{prospect.get("summary", "No summary available.")}

**Industry:** {prospect.get("industry", "Unknown")}
**Fit Score:** {prospect.get("fit_score", "N/A")}/100

---

## 2. Why They're a Good Fit

{prospect.get("fit_reason", "Matches ideal customer profile.")}

---

## 3. Decision Makers ({len(contacts)})

"""
    for c in contacts:
        packet += f"- **{c.get('name', 'Unknown')}** - {c.get('title', 'Contact')}"
        if c.get('email'):
            packet += f" ({c.get('email')})"
        packet += "\n"

    if not contacts:
        packet += "No contacts identified yet.\n"

    packet += f"""
---

## 4. Recommended Approach

1. Lead with {client_name}'s value proposition
2. Reference their specific challenges
3. Propose concrete next step (demo, call)

---

## 5. Drafted Email

"""
    if email:
        packet += f"""**To:** {email.get("to", "N/A")}
**Subject:** {email.get("subject", "N/A")}

---

{email.get("body", "No email body.")}
"""
    else:
        packet += "No email drafted yet.\n"

    packet += f"""
---

*Generated by CX AI Agent for {client_name}*
"""
    return packet


def get_prospect_choices():
    return [p["name"] for p in knowledge_base["prospects"]] if knowledge_base["prospects"] else []


# ============================================================================
# GRADIO UI
# ============================================================================
def get_logo_base64():
    """Load logo image as base64 for embedding in HTML"""
    logo_path = Path(__file__).parent / "assets" / "cx_ai_agent_logo_512.png"
    if logo_path.exists():
        with open(logo_path, "rb") as f:
            return base64.b64encode(f.read()).decode("utf-8")
    return None

def get_favicon_base64():
    """Load favicon as base64 for embedding"""
    favicon_path = Path(__file__).parent / "assets" / "cx_ai_agent_favicon_32.png"
    if favicon_path.exists():
        with open(favicon_path, "rb") as f:
            return base64.b64encode(f.read()).decode("utf-8")
    return None


def create_app():

    # Load logo as base64
    logo_b64 = get_logo_base64()
    favicon_b64 = get_favicon_base64()

    # Build sidebar logo HTML
    sidebar_logo = f'<img src="data:image/png;base64,{logo_b64}" class="sidebar-logo" alt="Logo">' if logo_b64 else '<div class="sidebar-logo" style="background:#0176D3;display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;">CX</div>'

    # Custom head HTML
    favicon_html = f'<link rel="icon" type="image/png" href="data:image/png;base64,{favicon_b64}">' if favicon_b64 else ''

    head_html = f"""
    {favicon_html}
    <meta name="theme-color" content="#0176D3">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // Sidebar toggle functionality - exposed on window for global access
        window.toggleSidebar = function() {{
            const sidebar = document.querySelector('.sidebar');
            const main = document.querySelector('.main-wrapper');
            sidebar.classList.toggle('collapsed');
            main.classList.toggle('expanded');
        }};

        window.toggleMobileSidebar = function() {{
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.querySelector('.sidebar-overlay');
            sidebar.classList.toggle('mobile-open');
            if (sidebar.classList.contains('mobile-open')) {{
                overlay.style.display = 'block';
            }} else {{
                overlay.style.display = 'none';
            }}
        }};

        window.closeMobileSidebar = function() {{
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.querySelector('.sidebar-overlay');
            sidebar.classList.remove('mobile-open');
            if (overlay) overlay.style.display = 'none';
        }};

        // Page navigation using CSS classes
        window._pageIds = ['setup', 'dashboard', 'discovery', 'prospects', 'contacts', 'emails', 'chat', 'about'];
        window._pageElementsCache = {{}};

        // Find page element - tries multiple approaches
        function findPageElement(pageId) {{
            // Check cache first
            if (window._pageElementsCache[pageId]) {{
                return window._pageElementsCache[pageId];
            }}

            let el = null;

            // Try direct ID
            el = document.getElementById('page-' + pageId);

            // Try querySelector with partial match
            if (!el) {{
                el = document.querySelector('[id*="page-' + pageId + '"]');
            }}

            // Try finding by data attribute
            if (!el) {{
                el = document.querySelector('[data-page="' + pageId + '"]');
            }}

            // Cache if found
            if (el) {{
                window._pageElementsCache[pageId] = el;
                console.log('Cached page element:', pageId, '->', el.id || el.className);
            }}

            return el;
        }}

        window.selectPage = function(pageName) {{
            console.log('selectPage called:', pageName);

            // Close mobile sidebar
            if (window.closeMobileSidebar) {{
                window.closeMobileSidebar();
            }}

            // Update active nav item
            document.querySelectorAll('.nav-item').forEach(function(item) {{
                item.classList.toggle('active', item.dataset.page === pageName);
            }});

            // Show/hide pages using class-based approach
            let foundCount = 0;
            window._pageIds.forEach(function(id) {{
                const el = findPageElement(id);
                if (el) {{
                    foundCount++;
                    if (id === pageName) {{
                        el.classList.remove('page-hidden');
                        el.style.display = 'flex';
                        console.log('SHOWING page:', id);
                    }} else {{
                        el.classList.add('page-hidden');
                        el.style.display = 'none';
                    }}
                }}
            }});

            if (foundCount === 0) {{
                console.error('No page elements found! Dumping DOM structure...');
                const mainWrapper = document.querySelector('.main-wrapper');
                if (mainWrapper) {{
                    console.log('main-wrapper children:', mainWrapper.children.length);
                    Array.from(mainWrapper.children).forEach(function(child, i) {{
                        console.log(i + ':', child.tagName, child.id, child.className.substring(0, 50));
                    }});
                }} else {{
                    console.log('main-wrapper not found!');
                }}
            }} else {{
                console.log('Found', foundCount, 'page elements');
            }}
        }};

        // Initialize on load
        document.addEventListener('DOMContentLoaded', function() {{
            // Handle overlay click to close sidebar
            const overlay = document.querySelector('.sidebar-overlay');
            if (overlay) {{
                overlay.addEventListener('click', window.closeMobileSidebar);
            }}

            // Initial page element discovery after Gradio loads
            setTimeout(function() {{
                console.log('Running initial page discovery...');
                window.selectPage('setup');
            }}, 1000);
        }});
    </script>
    """

    with gr.Blocks(
        title="CX AI Agent - B2B Sales Intelligence",
        theme=gr.themes.Soft(primary_hue="blue", secondary_hue="slate", neutral_hue="slate"),
        css=ENTERPRISE_CSS,
        head=head_html
    ) as demo:

        # ===== SIDEBAR (HTML) =====
        gr.HTML(f"""
        <!-- Mobile Header -->
        <div class="mobile-header">
            <button class="menu-btn" onclick="window.toggleMobileSidebar()">☰</button>
            <span class="title">CX AI Agent</span>
        </div>

        <!-- Sidebar Overlay (for mobile) -->
        <div class="sidebar-overlay" onclick="window.closeMobileSidebar()"></div>

        <!-- Sidebar Navigation -->
        <div class="sidebar" id="sidebar">
            <div class="sidebar-header">
                {sidebar_logo}
                <span class="sidebar-brand">CX AI Agent</span>
            </div>
            <button class="toggle-btn" onclick="window.toggleSidebar()">β—€</button>
            <nav class="sidebar-nav">
                <div class="nav-item active" data-page="setup" onclick="window.selectPage && window.selectPage('setup')">
                    <span class="nav-icon">βš™οΈ</span>
                    <span class="nav-text">Setup</span>
                </div>
                <div class="nav-item" data-page="dashboard" onclick="window.selectPage && window.selectPage('dashboard')">
                    <span class="nav-icon">πŸ“Š</span>
                    <span class="nav-text">Dashboard</span>
                </div>
                <div class="nav-item" data-page="discovery" onclick="window.selectPage && window.selectPage('discovery')">
                    <span class="nav-icon">πŸ”</span>
                    <span class="nav-text">Discovery</span>
                </div>
                <div class="nav-item" data-page="prospects" onclick="window.selectPage && window.selectPage('prospects')">
                    <span class="nav-icon">🎯</span>
                    <span class="nav-text">Prospects</span>
                </div>
                <div class="nav-item" data-page="contacts" onclick="window.selectPage && window.selectPage('contacts')">
                    <span class="nav-icon">πŸ‘₯</span>
                    <span class="nav-text">Contacts</span>
                </div>
                <div class="nav-item" data-page="emails" onclick="window.selectPage && window.selectPage('emails')">
                    <span class="nav-icon">βœ‰οΈ</span>
                    <span class="nav-text">Emails</span>
                </div>
                <div class="nav-item" data-page="chat" onclick="window.selectPage && window.selectPage('chat')">
                    <span class="nav-icon">πŸ’¬</span>
                    <span class="nav-text">AI Chat</span>
                </div>
                <div class="nav-item" data-page="about" onclick="window.selectPage && window.selectPage('about')">
                    <span class="nav-icon">ℹ️</span>
                    <span class="nav-text">About Us</span>
                </div>
            </nav>
        </div>
        """)

        # ===== MAIN CONTENT WRAPPER =====
        with gr.Column(elem_classes="main-wrapper"):

            # Hidden page selector for navigation state
            page_selector = gr.Textbox(value="setup", visible=False, elem_id="page-selector")

            # Navigation buttons row (hidden on desktop, visible on mobile as fallback)
            with gr.Row(elem_classes="nav-buttons-row", visible=True):
                btn_setup = gr.Button("βš™οΈ Setup", elem_id="btn-setup", size="sm")
                btn_dashboard = gr.Button("πŸ“Š Dashboard", elem_id="btn-dashboard", size="sm")
                btn_discovery = gr.Button("πŸ” Discovery", elem_id="btn-discovery", size="sm")
                btn_prospects = gr.Button("🎯 Prospects", elem_id="btn-prospects", size="sm")
                btn_contacts = gr.Button("πŸ‘₯ Contacts", elem_id="btn-contacts", size="sm")
                btn_emails = gr.Button("βœ‰οΈ Emails", elem_id="btn-emails", size="sm")
                btn_chat = gr.Button("πŸ’¬ Chat", elem_id="btn-chat", size="sm")
                btn_about = gr.Button("ℹ️ About", elem_id="btn-about", size="sm")

            # ===== SETUP PAGE =====
            with gr.Column(visible=True, elem_id="page-setup") as setup_page:
                gr.HTML("""
                <div class="page-header">
                    <div>
                        <h1 class="page-title">βš™οΈ Setup</h1>
                        <p class="page-subtitle">Configure your company and API credentials</p>
                    </div>
                </div>

                <div class="info-box">
                    <span class="info-box-icon">πŸš€</span>
                    <div class="info-box-content">
                        <div class="info-box-title">Getting Started</div>
                        <div class="info-box-text">
                            Complete these steps to start finding prospects:
                            <ul>
                                <li><strong>HuggingFace Token</strong> - Required for AI-powered research and email drafting</li>
                                <li><strong>Serper API Key</strong> - Optional, enables real-time web search for company info</li>
                                <li><strong>Company Name</strong> - Your company name helps AI find relevant prospects</li>
                            </ul>
                        </div>
                    </div>
                </div>
                """)

                with gr.Row():
                    with gr.Column(scale=1):
                        gr.HTML("""<div class="form-section">
                            <h3 style="margin:0 0 12px 0; color: var(--text-primary);">πŸ”‘ API Credentials</h3>
                            <p style="color: var(--text-secondary); font-size: 14px; margin-bottom: 16px;">
                                Enter your HuggingFace token to enable AI features.
                                <a href="https://huggingface.co/settings/tokens" target="_blank">Get a free token β†’</a>
                            </p>
                        </div>""")

                        hf_token_input = gr.Textbox(
                            label="HuggingFace Token",
                            placeholder="hf_xxxxxxxxxx",
                            type="password"
                        )

                        serper_key_input = gr.Textbox(
                            label="Serper API Key (Optional)",
                            placeholder="For web search - get at serper.dev",
                            type="password"
                        )

                        gr.HTML("""<div class="form-section" style="margin-top: 20px;">
                            <h3 style="margin:0 0 12px 0; color: var(--text-primary);">🏒 Your Company</h3>
                            <p style="color: var(--text-secondary); font-size: 14px; margin-bottom: 16px;">
                                AI will research your company and find matching prospects.
                            </p>
                        </div>""")

                        client_name_input = gr.Textbox(label="Company Name", placeholder="e.g., Acme Corp")

                        with gr.Row():
                            setup_btn = gr.Button("πŸš€ Setup Company", variant="primary", size="lg")
                            reset_btn = gr.Button("πŸ—‘οΈ Reset", variant="stop", size="sm")

                    with gr.Column(scale=2):
                        setup_output = gr.Markdown("*Enter your credentials and company name to begin.*")

            # ===== DASHBOARD PAGE =====
            with gr.Column(visible=True, elem_id="page-dashboard", elem_classes="page-hidden") as dashboard_page:
                gr.HTML("""<div class="page-header"><div>
                    <h1 class="page-title">πŸ“Š Dashboard</h1>
                    <p class="page-subtitle">Overview of your sales pipeline</p>
                </div></div>

                <div class="info-box success">
                    <span class="info-box-icon">πŸ“ˆ</span>
                    <div class="info-box-content">
                        <div class="info-box-title">Pipeline Overview</div>
                        <div class="info-box-text">
                            Track your progress at a glance. The dashboard shows real-time counts of prospects discovered, contacts found, and emails drafted. Click "Refresh" to update the stats after running Discovery.
                        </div>
                    </div>
                </div>
                """)

                client_status = gr.HTML(get_client_status_html())

                gr.HTML('<div class="stats-grid">')
                with gr.Row():
                    prospects_stat = gr.HTML(get_stat_html("0", "Prospects Found", "var(--primary-blue)"))
                    contacts_stat = gr.HTML(get_stat_html("0", "Decision Makers", "var(--success-green)"))
                    emails_stat = gr.HTML(get_stat_html("0", "Emails Drafted", "var(--warning-orange)"))
                    gr.HTML(get_stat_html("Qwen3-32B", "AI Model", "var(--purple)"))

                refresh_btn = gr.Button("πŸ”„ Refresh Dashboard", variant="secondary")

            # ===== DISCOVERY PAGE =====
            with gr.Column(visible=True, elem_id="page-discovery", elem_classes="page-hidden") as discovery_page:
                gr.HTML("""<div class="page-header"><div>
                    <h1 class="page-title">πŸ” Discovery</h1>
                    <p class="page-subtitle">AI-powered prospect discovery</p>
                </div></div>

                <div class="info-box tip">
                    <span class="info-box-icon">πŸ’‘</span>
                    <div class="info-box-content">
                        <div class="info-box-title">How Discovery Works</div>
                        <div class="info-box-text">
                            <ul>
                                <li><strong>Step 1:</strong> AI searches the web for companies matching your profile</li>
                                <li><strong>Step 2:</strong> Finds decision-makers (CEOs, VPs, Founders) with verified emails</li>
                                <li><strong>Step 3:</strong> Drafts personalized outreach emails for each contact</li>
                            </ul>
                            <em>Tip: Start with 2-3 prospects to test, then increase the number.</em>
                        </div>
                    </div>
                </div>
                """)

                client_status_2 = gr.HTML(get_client_status_html())

                with gr.Row():
                    with gr.Column(scale=1):
                        gr.HTML("""<div class="action-card">
                            <h3>Find Prospects</h3>
                            <p>AI will search for companies, find decision-makers with verified contacts, and draft personalized emails.</p>
                        </div>""")
                        num_prospects = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="Number of prospects")
                        discover_btn = gr.Button("πŸ” Find Prospects & Contacts", variant="primary", size="lg")

                    with gr.Column(scale=2):
                        discovery_output = gr.HTML("<p style='color: var(--text-secondary); font-style: italic;'>Click 'Find Prospects' after completing Setup.</p>")

            # ===== PROSPECTS PAGE =====
            with gr.Column(visible=True, elem_id="page-prospects", elem_classes="page-hidden") as prospects_page:
                gr.HTML("""<div class="page-header"><div>
                    <h1 class="page-title">🎯 Prospects</h1>
                    <p class="page-subtitle">Companies discovered by AI</p>
                </div></div>

                <div class="info-box">
                    <span class="info-box-icon">🏒</span>
                    <div class="info-box-content">
                        <div class="info-box-title">Your Prospect Companies</div>
                        <div class="info-box-text">
                            This list shows all companies found by the AI. Each prospect includes company details, industry, and a fit score (0-100) indicating how well they match your ideal customer profile. Higher scores = better fit!
                        </div>
                    </div>
                </div>
                """)
                refresh_prospects_btn = gr.Button("πŸ”„ Refresh", variant="secondary", size="sm")
                prospects_list = gr.HTML(get_prospects_html())

            # ===== CONTACTS PAGE =====
            with gr.Column(visible=True, elem_id="page-contacts", elem_classes="page-hidden") as contacts_page:
                gr.HTML("""<div class="page-header"><div>
                    <h1 class="page-title">πŸ‘₯ Contacts</h1>
                    <p class="page-subtitle">Decision makers found by AI</p>
                </div></div>

                <div class="info-box">
                    <span class="info-box-icon">πŸ‘€</span>
                    <div class="info-box-content">
                        <div class="info-box-title">Decision Maker Contacts</div>
                        <div class="info-box-text">
                            AI finds key decision-makers (CEOs, VPs, Founders, Directors) at each prospect company. Contact info includes name, title, email, and company. Only verified contacts with real email addresses are shown.
                        </div>
                    </div>
                </div>
                """)
                refresh_contacts_btn = gr.Button("πŸ”„ Refresh", variant="secondary", size="sm")
                contacts_list = gr.HTML(get_contacts_html())

            # ===== EMAILS PAGE =====
            with gr.Column(visible=True, elem_id="page-emails", elem_classes="page-hidden") as emails_page:
                gr.HTML("""<div class="page-header"><div>
                    <h1 class="page-title">βœ‰οΈ Emails</h1>
                    <p class="page-subtitle">AI-drafted outreach emails</p>
                </div></div>

                <div class="info-box tip">
                    <span class="info-box-icon">✍️</span>
                    <div class="info-box-content">
                        <div class="info-box-title">AI-Written Outreach Emails</div>
                        <div class="info-box-text">
                            Each email is personalized based on the prospect's company, industry, and any pain points discovered during research. Review and customize before sending. Emails are designed to start conversations, not close deals.
                        </div>
                    </div>
                </div>
                """)
                refresh_emails_btn = gr.Button("πŸ”„ Refresh", variant="secondary", size="sm")
                emails_list = gr.HTML(get_emails_html())

            # ===== AI CHAT PAGE =====
            with gr.Column(visible=True, elem_id="page-chat", elem_classes="page-hidden") as chat_page:
                gr.HTML("""<div class="page-header"><div>
                    <h1 class="page-title">πŸ’¬ AI Chat</h1>
                    <p class="page-subtitle">AI-powered communication hub</p>
                </div></div>""")

                with gr.Tabs(elem_classes="chat-subtabs"):
                    # ----- SUB-TAB 1: Internal Sales Assistant -----
                    with gr.Tab("🎯 Sales Assistant", elem_id="tab-sales-assistant"):
                        gr.HTML("""
                        <div class="info-box success">
                            <span class="info-box-icon">πŸ€–</span>
                            <div class="info-box-content">
                                <div class="info-box-title">Your AI Sales Assistant</div>
                                <div class="info-box-text">
                                    Chat with AI to research companies, draft emails, get talking points, or manage your pipeline. The AI has access to all your prospect data and can perform web searches for real-time info.
                                </div>
                            </div>
                        </div>
                        """)

                        chatbot = gr.Chatbot(value=[], height=350, label="Sales Assistant Chat")

                        with gr.Row():
                            chat_input = gr.Textbox(
                                label="Message",
                                placeholder="Ask about prospects, search for companies, draft emails...",
                                lines=1,
                                scale=4
                            )
                            send_btn = gr.Button("Send", variant="primary", scale=1)

                        gr.HTML("""<div class="action-card" style="margin-top: 16px;">
                            <h4>πŸ’‘ Try These Prompts</h4>
                            <ul style="font-size: 13px; line-height: 1.8; margin: 8px 0 0 0; padding-left: 20px;">
                                <li>"Search for DTC fashion brands that raised Series A"</li>
                                <li>"Draft an email to the CEO of Warby Parker"</li>
                                <li>"Give me talking points for my call with Glossier"</li>
                                <li>"Summary of all prospects and their status"</li>
                            </ul>
                        </div>""")

                    # ----- SUB-TAB 2: Prospect-Facing AI Chat -----
                    with gr.Tab("πŸ‘€ Prospect Chat Demo", elem_id="tab-prospect-chat"):
                        gr.HTML("""
                        <div class="info-box tip">
                            <span class="info-box-icon">πŸ’¬</span>
                            <div class="info-box-content">
                                <div class="info-box-title">Prospect Communication Demo</div>
                                <div class="info-box-text">
                                    This demonstrates how prospects can interact with your company's AI assistant. The AI can answer questions about your products/services, qualify leads, schedule meetings, and escalate to human agents when needed.
                                </div>
                            </div>
                        </div>
                        """)

                        prospect_chatbot = gr.Chatbot(
                            value=[],
                            height=350,
                            label="Prospect Chat",
                            avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=cx-agent")
                        )

                        with gr.Row():
                            prospect_input = gr.Textbox(
                                label="Prospect Message",
                                placeholder="Hi, I'm interested in learning more about your services...",
                                lines=1,
                                scale=4
                            )
                            prospect_send_btn = gr.Button("Send", variant="primary", scale=1)

                        with gr.Row():
                            with gr.Column(scale=2):
                                gr.HTML("""<div class="action-card">
                                    <h4>🎭 Demo Scenario</h4>
                                    <p style="font-size: 13px; margin-bottom: 8px;">You are a prospect visiting the client's website. The AI will:</p>
                                    <ul style="font-size: 13px; line-height: 1.6; margin: 0; padding-left: 20px;">
                                        <li>Answer questions about products and services</li>
                                        <li>Qualify you as a lead based on your needs</li>
                                        <li>Offer to schedule a meeting with sales</li>
                                        <li>Escalate complex inquiries to human agents</li>
                                    </ul>
                                </div>""")

                            with gr.Column(scale=1):
                                gr.HTML("""<div class="action-card">
                                    <h4>⚑ Quick Actions</h4>
                                </div>""")
                                generate_handoff_btn = gr.Button("πŸ“‹ Generate Handoff Packet", variant="secondary", size="sm")
                                escalate_btn = gr.Button("🚨 Escalate to Human", variant="stop", size="sm")
                                schedule_btn = gr.Button("πŸ“… Schedule Meeting", variant="secondary", size="sm")

                        handoff_output = gr.Markdown(visible=False, elem_classes="handoff-packet")

            # ===== ABOUT US PAGE =====
            with gr.Column(visible=True, elem_id="page-about", elem_classes="page-hidden") as about_page:
                gr.HTML("""<div class="page-header"><div>
                    <h1 class="page-title">ℹ️ About Us</h1>
                    <p class="page-subtitle">Learn more about CX AI Agent</p>
                </div></div>""")

                gr.Markdown("""
# πŸ€– CX AI Agent - B2B Sales Intelligence Platform

[![Enterprise Application](https://img.shields.io/badge/MCP-Enterprise%20Track-blue)](https://github.com)
[![Powered by AI](https://img.shields.io/badge/Powered%20by-HuggingFace-yellow)](https://huggingface.co)
[![Gradio](https://img.shields.io/badge/Built%20with-Gradio-orange)](https://gradio.app)

> **πŸ† MCP in Action Track - Enterprise Applications**
>
> Tag: `mcp-in-action-track-enterprise`

---

## πŸ“‹ Overview

**CX AI Agent** is an AI-powered B2B sales automation platform that helps sales teams discover prospects, find decision-makers, and draft personalized outreach emailsβ€”all powered by autonomous AI agents using the Model Context Protocol (MCP).

### 🎯 Key Features

| Feature | Description |
|---------|-------------|
| **πŸ” AI Discovery** | Automatically find and research prospect companies matching your ideal customer profile |
| **πŸ‘₯ Contact Finder** | Locate decision-makers (CEOs, VPs, Founders) with verified email addresses |
| **βœ‰οΈ Email Drafting** | Generate personalized cold outreach emails based on company research |
| **πŸ’¬ AI Chat** | Interactive assistant for pipeline management and real-time research |
| **πŸ‘€ Prospect Chat** | Demo of prospect-facing AI with handoff & escalation capabilities |
| **πŸ“Š Dashboard** | Real-time pipeline metrics and progress tracking |

---

## πŸ—οΈ Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                      CX AI Agent                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”‚
β”‚  β”‚   Gradio   β”‚  β”‚  Autonomousβ”‚  β”‚    MCP     β”‚         β”‚
β”‚  β”‚     UI     │──│    Agent   │──│   Servers  β”‚         β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β”‚
β”‚         β”‚                β”‚                β”‚             β”‚
β”‚         β–Ό                β–Ό                β–Ό             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”‚
β”‚  β”‚              MCP Tool Definitions           β”‚        β”‚
β”‚  β”‚  β€’ Search (Web, News)                       β”‚        β”‚
β”‚  β”‚  β€’ Store (Prospects, Contacts, Facts)       β”‚        β”‚
β”‚  β”‚  β€’ Email (Send, Thread Management)          β”‚        β”‚
β”‚  β”‚  β€’ Calendar (Meeting Slots, Invites)        β”‚        β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## πŸš€ Getting Started

### Prerequisites

- Python 3.8+
- HuggingFace API Token ([Get one free](https://huggingface.co/settings/tokens))
- Serper API Key (Optional, for web search)

### Quick Start

1. **Setup**: Enter your API credentials and company name
2. **Discover**: Let AI find prospects matching your profile
3. **Review**: Check discovered companies and contacts
4. **Engage**: Use AI-drafted emails for outreach

---

## πŸ”§ MCP Tools Available

### Search MCP Server
- `search_web` - Search the web for company information
- `search_news` - Find recent news about companies

### Store MCP Server
- `save_prospect` / `get_prospect` / `list_prospects` - Manage prospects
- `save_company` / `get_company` - Store company data
- `save_contact` / `list_contacts_by_domain` - Manage contacts
- `save_fact` - Store research insights
- `discover_prospects_with_contacts` - Full discovery pipeline
- `find_verified_contacts` - Find decision-makers
- `check_suppression` - Compliance checking

### Email MCP Server
- `send_email` - Send outreach emails
- `get_email_thread` - Retrieve conversation history

### Calendar MCP Server
- `suggest_meeting_slots` - Generate available times
- `generate_calendar_invite` - Create .ics files

---

## 🎭 Prospect Chat Demo

The **Prospect Chat Demo** tab showcases how prospects can interact with your company's AI:

- **Lead Qualification**: AI asks qualifying questions to understand prospect needs
- **Handoff Packets**: Generate comprehensive summaries for human sales reps
- **Escalation Flows**: Automatically escalate complex inquiries to humans
- **Meeting Scheduling**: Integrate with calendar for instant booking

---

## πŸ“Š Technology Stack

| Component | Technology |
|-----------|------------|
| **Frontend** | Gradio 5.x |
| **AI Model** | Qwen3-32B via HuggingFace |
| **Protocol** | Model Context Protocol (MCP) |
| **Search** | Serper API |
| **Language** | Python 3.8+ |

---

## πŸ“ License

This project is open source and available under the MIT License.

---

## πŸ™ Acknowledgments

- **Anthropic** - Model Context Protocol specification
- **HuggingFace** - AI model hosting and inference
- **Gradio** - UI framework
- **Serper** - Web search API

---

## πŸ‘¨β€πŸ’» Developer

**Syed Muzakkir Hussain**

[![HuggingFace Profile](https://img.shields.io/badge/HuggingFace-muzakkirhussain011-yellow?logo=huggingface)](https://huggingface.co/muzakkirhussain011)

[https://huggingface.co/muzakkirhussain011](https://huggingface.co/muzakkirhussain011)

---

<div align="center">

**Built with ❀️ by [Syed Muzakkir Hussain](https://huggingface.co/muzakkirhussain011) for the Gradio Agents & MCP Hackathon 2025**

`mcp-in-action-track-enterprise`

</div>
                """)

        # Footer
        gr.HTML("""
        <div class="footer">
            <p><strong>CX AI Agent</strong> β€” Automated B2B Sales Intelligence</p>
            <p style="font-size: 12px;">Powered by AI β€’ Β© 2025</p>
        </div>
        """)

        # ===== NAVIGATION HANDLERS =====

        all_pages = [setup_page, dashboard_page, discovery_page, prospects_page, contacts_page, emails_page, chat_page, about_page]

        def show_page(page_name):
            """Return visibility updates for all pages"""
            pages = {
                "setup": [True, False, False, False, False, False, False, False],
                "dashboard": [False, True, False, False, False, False, False, False],
                "discovery": [False, False, True, False, False, False, False, False],
                "prospects": [False, False, False, True, False, False, False, False],
                "contacts": [False, False, False, False, True, False, False, False],
                "emails": [False, False, False, False, False, True, False, False],
                "chat": [False, False, False, False, False, False, True, False],
                "about": [False, False, False, False, False, False, False, True],
            }
            visibility = pages.get(page_name, pages["setup"])
            return [gr.update(visible=v) for v in visibility]

        # When page_selector textbox changes, update page visibility
        page_selector.change(fn=show_page, inputs=[page_selector], outputs=all_pages)

        # Connect navigation buttons to pages
        btn_setup.click(fn=lambda: show_page("setup"), outputs=all_pages)
        btn_dashboard.click(fn=lambda: show_page("dashboard"), outputs=all_pages)
        btn_discovery.click(fn=lambda: show_page("discovery"), outputs=all_pages)
        btn_prospects.click(fn=lambda: show_page("prospects"), outputs=all_pages)
        btn_contacts.click(fn=lambda: show_page("contacts"), outputs=all_pages)
        btn_emails.click(fn=lambda: show_page("emails"), outputs=all_pages)
        btn_chat.click(fn=lambda: show_page("chat"), outputs=all_pages)
        btn_about.click(fn=lambda: show_page("about"), outputs=all_pages)

        # Navigation JavaScript is now in head_html for earlier loading

        # ===== EVENT HANDLERS =====

        # Setup button - run setup and then update status indicators
        setup_btn.click(
            fn=setup_client_company,
            inputs=[client_name_input, hf_token_input, serper_key_input],
            outputs=[setup_output]
        ).then(
            fn=lambda: (get_client_status_html(), get_client_status_html()),
            outputs=[client_status, client_status_2]
        )

        reset_btn.click(
            fn=reset_all_data,
            outputs=[prospects_stat, contacts_stat, emails_stat, client_status, prospects_list, emails_list,
                     contacts_list, client_name_input, setup_output, discovery_output]
        )

        def refresh_dashboard():
            stats = get_dashboard_stats()
            return stats[0], stats[1], stats[2], stats[3]

        refresh_btn.click(fn=refresh_dashboard, outputs=[prospects_stat, contacts_stat, emails_stat, client_status])

        # Discover prospects and then update all lists
        discover_btn.click(
            fn=discover_prospects,
            inputs=[num_prospects],
            outputs=[discovery_output]
        ).then(
            fn=lambda: (get_prospects_html(), get_contacts_html(), get_emails_html()),
            outputs=[prospects_list, contacts_list, emails_list]
        ).then(
            fn=refresh_dashboard,
            outputs=[prospects_stat, contacts_stat, emails_stat, client_status]
        )

        refresh_prospects_btn.click(fn=get_prospects_html, outputs=[prospects_list])
        refresh_contacts_btn.click(fn=get_contacts_html, outputs=[contacts_list])
        refresh_emails_btn.click(fn=get_emails_html, outputs=[emails_list])

        # Async chat wrapper that uses session token
        async def chat_async_wrapper(message, history):
            token = session_hf_token.get("token", "")
            final_result = (history, "")
            async for result in chat_with_ai_async(message, history, token):
                final_result = result
            return final_result

        send_btn.click(fn=chat_async_wrapper, inputs=[chat_input, chatbot], outputs=[chatbot, chat_input])
        chat_input.submit(fn=chat_async_wrapper, inputs=[chat_input, chatbot], outputs=[chatbot, chat_input])

        # ===== PROSPECT CHAT HANDLERS =====

        async def prospect_chat_wrapper(message, history):
            """Handle prospect-facing chat with company representative AI"""
            if not message.strip():
                return history, ""

            # Get client company info for context
            client_info = knowledge_base["client"].get("name") or "Our Company"

            # Build prospect-facing system context
            system_context = f"""You are an AI assistant representing {client_info}. You are speaking with a potential prospect who is interested in learning about the company's products and services.

Your role is to:
1. Answer questions about the company professionally and helpfully
2. Qualify the prospect by understanding their needs, company size, and timeline
3. Offer to schedule meetings with sales representatives when appropriate
4. Escalate complex technical or pricing questions to human agents

Be friendly, professional, and helpful. Focus on understanding the prospect's needs."""

            history = history + [[message, None]]

            # Use the AI to generate response
            token = session_hf_token.get("token", "")
            if token:
                try:
                    from huggingface_hub import InferenceClient
                    client = InferenceClient(token=token)

                    messages = [{"role": "system", "content": system_context}]
                    for h in history[:-1]:
                        if h[0]:
                            messages.append({"role": "user", "content": h[0]})
                        if h[1]:
                            messages.append({"role": "assistant", "content": h[1]})
                    messages.append({"role": "user", "content": message})

                    response = client.chat_completion(
                        model="Qwen/Qwen2.5-72B-Instruct",
                        messages=messages,
                        max_tokens=500
                    )
                    reply = response.choices[0].message.content
                except Exception as e:
                    reply = f"I apologize, I'm having trouble connecting right now. Please try again or contact us directly. (Error: {str(e)[:50]})"
            else:
                reply = f"Thank you for your interest in {client_info}! I'd be happy to help you learn more about our solutions. What specific challenges are you looking to address?"

            history[-1][1] = reply
            return history, ""

        def generate_handoff_packet(chat_history):
            """Generate a handoff packet from the prospect conversation"""
            if not chat_history:
                return gr.update(visible=True, value="**⚠️ No conversation to generate handoff from.** Start a conversation first.")

            # Extract key info from conversation
            conversation_text = "\n".join([f"Prospect: {h[0]}\nAgent: {h[1]}" for h in chat_history if h[0] and h[1]])

            client_name = knowledge_base["client"].get("name") or "Unknown Client"

            packet = f"""
## πŸ“‹ Handoff Packet

**Generated:** {datetime.now().strftime("%Y-%m-%d %H:%M")}
**Client Company:** {client_name}

---

### πŸ“ Conversation Summary

{len(chat_history)} messages exchanged with prospect.

### πŸ’¬ Full Conversation Log

```
{conversation_text[:1500]}{'...' if len(conversation_text) > 1500 else ''}
```

### 🎯 Recommended Actions

1. Review conversation for prospect pain points
2. Prepare personalized follow-up materials
3. Schedule discovery call within 24-48 hours

### πŸ“Š Lead Score: Pending Assessment

---

*This packet was auto-generated by CX AI Agent*
"""
            return gr.update(visible=True, value=packet)

        def escalate_to_human(chat_history):
            """Escalate conversation to human agent"""
            if not chat_history:
                return gr.update(visible=True, value="**🚨 Escalation Created**\n\nNo conversation history to escalate. A human agent will reach out to assist you.")

            return gr.update(visible=True, value=f"""
## 🚨 Escalation Created

**Status:** Pending Human Review
**Priority:** High
**Timestamp:** {datetime.now().strftime("%Y-%m-%d %H:%M")}

A human sales representative will review this conversation and reach out shortly.

**Messages in thread:** {len(chat_history)}
""")

        def schedule_meeting():
            """Generate meeting scheduling info"""
            from datetime import timedelta
            now = datetime.now()
            slots = []
            for i in range(1, 4):
                day = now + timedelta(days=i)
                if day.weekday() < 5:  # Weekdays only
                    slots.append(f"- {day.strftime('%A, %B %d')} at 10:00 AM EST")
                    slots.append(f"- {day.strftime('%A, %B %d')} at 2:00 PM EST")

            return gr.update(visible=True, value=f"""
## πŸ“… Meeting Scheduling

**Available Time Slots:**

{chr(10).join(slots[:4])}

To schedule a meeting, please reply with your preferred time slot, or [click here](#) to access our calendar booking system.

*Times shown in EST. Meetings are typically 30 minutes.*
""")

        # Connect prospect chat handlers
        prospect_send_btn.click(
            fn=prospect_chat_wrapper,
            inputs=[prospect_input, prospect_chatbot],
            outputs=[prospect_chatbot, prospect_input]
        )
        prospect_input.submit(
            fn=prospect_chat_wrapper,
            inputs=[prospect_input, prospect_chatbot],
            outputs=[prospect_chatbot, prospect_input]
        )

        # Connect action buttons
        generate_handoff_btn.click(fn=generate_handoff_packet, inputs=[prospect_chatbot], outputs=[handoff_output])
        escalate_btn.click(fn=escalate_to_human, inputs=[prospect_chatbot], outputs=[handoff_output])
        schedule_btn.click(fn=schedule_meeting, outputs=[handoff_output])

    return demo


if __name__ == "__main__":
    demo = create_app()
    demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)