File size: 30,547 Bytes
2f14900
 
 
 
 
 
 
 
 
bba2b6a
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
 
 
132ab38
 
 
 
 
 
 
 
 
3f0124c
2f14900
132ab38
3f0124c
132ab38
 
3f0124c
2f14900
 
3f0124c
2f14900
132ab38
3f0124c
2f14900
 
3f0124c
2f14900
 
3f0124c
 
2f14900
 
3f0124c
 
 
132ab38
3f0124c
2f14900
 
3f0124c
 
 
 
 
2f14900
 
3f0124c
2f14900
132ab38
3f0124c
132ab38
3f0124c
 
132ab38
2f14900
 
132ab38
 
 
2f14900
 
132ab38
3f0124c
132ab38
 
 
 
 
2f14900
132ab38
 
 
3f0124c
132ab38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
132ab38
 
 
 
 
 
2f14900
3f0124c
 
2f14900
3f0124c
 
 
 
 
 
 
 
 
 
2f14900
3f0124c
 
 
2f14900
3f0124c
2f14900
132ab38
3f0124c
 
 
 
2f14900
3f0124c
132ab38
3f0124c
 
 
2f14900
 
132ab38
3f0124c
 
 
 
 
 
 
2f14900
3f0124c
2f14900
 
 
132ab38
3f0124c
132ab38
3f0124c
2f14900
3f0124c
2f14900
3f0124c
132ab38
2f14900
3f0124c
 
 
132ab38
2f14900
 
3f0124c
2f14900
132ab38
 
3f0124c
 
132ab38
 
 
2f14900
 
132ab38
 
2f14900
 
3f0124c
 
 
 
2f14900
3f0124c
 
 
 
 
 
 
2f14900
 
3f0124c
 
 
 
 
 
132ab38
3f0124c
132ab38
3f0124c
 
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
2f14900
3f0124c
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
2f14900
 
 
 
 
3f0124c
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
 
 
 
 
 
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bba2b6a
 
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
2f14900
 
 
 
 
 
 
 
 
 
 
 
3f0124c
 
 
 
 
2f14900
 
 
 
 
 
 
 
3f0124c
 
2f14900
3f0124c
bba2b6a
 
2f14900
 
3f0124c
 
 
 
 
 
 
 
2f14900
 
 
 
3f0124c
 
 
 
2f14900
 
 
 
 
 
 
 
 
 
 
3f0124c
 
 
 
 
 
 
 
 
 
bba2b6a
 
3f0124c
 
 
 
 
 
 
 
 
 
 
 
2f14900
3f0124c
 
bbfdbde
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
2f14900
3f0124c
2f14900
3f0124c
 
 
 
 
 
2f14900
3f0124c
 
 
bba2b6a
 
3f0124c
 
 
 
 
 
 
 
 
 
 
 
2f14900
 
 
3f0124c
 
2f14900
 
 
 
 
 
 
3f0124c
 
 
 
 
 
 
 
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bba2b6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59aec0c
 
 
 
 
 
 
 
 
 
bba2b6a
 
 
 
 
 
 
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
2f14900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0124c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bba2b6a
 
3f0124c
 
 
 
2f14900
 
 
 
 
 
bba2b6a
3f0124c
2f14900
 
3f0124c
bba2b6a
3f0124c
2f14900
 
 
 
 
 
 
 
 
 
 
 
bba2b6a
3f0124c
bba2b6a
 
2f14900
 
 
 
 
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
"""
app.py โ€“ Main Streamlit application
=====================================
CareerBot: AI-powered Indian Job Search Assistant
Track A | Week 1-2 Milestone
"""

import json
import os
import asyncio
import streamlit as st
from dotenv import load_dotenv

import database as db
from utils import (
    ALL_CITIES, EXPERIENCE_LEVELS, NOTICE_PERIODS,
    SALARY_RANGES, JOB_DOMAINS, truncate,
)

load_dotenv()

# ---------------------------------------------------------------------------
# Page config (MUST be first Streamlit call)
# ---------------------------------------------------------------------------
st.set_page_config(
    page_title="CareerBot โ€“ AI Job Search for India",
    page_icon="๐Ÿค–",
    layout="wide",
    initial_sidebar_state="expanded",
)

# ---------------------------------------------------------------------------
# Custom CSS โ€“ modern dark-themed UI
# ---------------------------------------------------------------------------
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Inter:wght@300;400;500;600;700&display=swap');

:root {
    --primary: #ffffff;
    --primary-glow: rgba(255, 255, 255, 0.2);
    --secondary: #cccccc;
    --accent: #ffffff;
    --bg-dark: #000000;
    --card-bg: #0a0a0a;
    --card-border: #1a1a1a;
    --text-main: #ffffff;
    --text-muted: #888888;
}

html, body, [class*="css"], .stApp {
    font-family: 'Outfit', 'Inter', sans-serif;
    background-color: #000000 !important;
    background-image: none !important;
    color: var(--text-main);
}

/* Glassmorphism containers */
[data-testid="stSidebar"] {
    background-color: #050505 !important;
    border-right: 1px solid var(--card-border);
}

/* Header Aesthetics */
.main-header {
    text-align: center;
    padding: 2.5rem 0 1.5rem;
    animation: fadeInDown 0.8s ease-out;
}
.main-header h1 {
    font-size: 3.5rem;
    font-weight: 800;
    letter-spacing: -0.02em;
    color: #ffffff;
    margin-bottom: 0.5rem;
}
.main-header p {
    color: var(--text-muted);
    font-size: 1.1rem;
    font-weight: 400;
    letter-spacing: 0.05em;
    text-transform: uppercase;
}

/* Premium Job Card */
.job-card {
    background-color: var(--card-bg);
    border: 1px solid var(--card-border);
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1.2rem;
    transition: all 0.3s ease;
}
.job-card:hover {
    transform: translateY(-2px);
    border-color: #333333;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.8);
}
.job-title {
    font-size: 1.4rem;
    font-weight: 700;
    color: #ffffff;
    margin-bottom: 0.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.company-name {
    color: var(--text-muted);
    font-weight: 500;
    font-size: 1rem;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.job-meta {
    font-size: 0.9rem;
    color: #aaaaaa;
    display: flex;
    gap: 1.2rem;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px dashed var(--card-border);
}
.job-apply-btn {
    display: inline-block;
    background-color: #ffffff;
    color: #000000 !important;
    padding: 0.6rem 1.5rem;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    font-size: 0.9rem;
    transition: all 0.3s ease;
}
.job-apply-btn:hover {
    background-color: #cccccc;
    transform: scale(1.02);
}

/* Badges */
.badge {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 10px;
    padding: 0.3rem 0.8rem;
    font-size: 0.85rem;
    font-weight: 500;
    color: #f1f5f9;
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
}
.badge-green  { background: rgba(16, 185, 129, 0.1); border-color: rgba(16, 185, 129, 0.3); color: #34d399; }
.badge-blue   { background: rgba(59, 130, 246, 0.1); border-color: rgba(59, 130, 246, 0.3); color: #60a5fa; }
.badge-purple { background: rgba(139, 92, 246, 0.1); border-color: rgba(139, 92, 246, 0.3); color: #a78bfa; }

/* Premium Chat */
.chat-user {
    background-color: #1a1a1a;
    border-radius: 20px 20px 4px 20px;
    padding: 1rem 1.25rem;
    margin: 0.75rem 0;
    max-width: 80%;
    margin-left: auto;
    color: white;
    border: 1px solid #333333;
    font-size: 0.95rem;
    line-height: 1.5;
    animation: slideInRight 0.4s ease-out;
}
.chat-bot {
    background-color: var(--card-bg);
    border: 1px solid var(--card-border);
    border-radius: 20px 20px 20px 4px;
    padding: 1rem 1.25rem;
    margin: 0.75rem 0;
    max-width: 85%;
    color: var(--text-main);
    font-size: 0.95rem;
    line-height: 1.6;
    animation: slideInLeft 0.4s ease-out;
}

.metric-box {
    background-color: var(--card-bg);
    border: 1px solid var(--card-border);
    border-radius: 12px;
    padding: 1.5rem;
    text-align: center;
    transition: all 0.3s ease;
}
.metric-box:hover {
    border-color: #444444;
}
.metric-box .metric-val {
    font-size: 2.2rem;
    font-weight: 800;
    color: #ffffff;
}

/* UI Elements */
.stButton > button {
    background-color: #ffffff !important;
    color: #000000 !important;
    border: none !important;
    padding: 0.6rem 2rem !important;
    border-radius: 8px !important;
    font-weight: 700 !important;
    transition: all 0.3s ease !important;
}
.stButton > button:hover {
    background-color: #cccccc !important;
    color: #000000 !important;
}

/* Animations */
@keyframes fadeInDown {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
}
@keyframes slideInRight {
    from { opacity: 0; transform: translateX(30px); }
    to { opacity: 1; transform: translateX(0); }
}
@keyframes slideInLeft {
    from { opacity: 0; transform: translateX(-30px); }
    to { opacity: 1; transform: translateX(0); }
}

/* Hide Streamlit components */
#MainMenu { visibility: hidden; }
footer { visibility: hidden; }

/* Custom Scrollbar */
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background-color: #000000; }
::-webkit-scrollbar-thumb { 
    background-color: #333333;
    border-radius: 10px;
}
</style>
""", unsafe_allow_html=True)

# ---------------------------------------------------------------------------
# Session state initialisation
# ---------------------------------------------------------------------------
def init_session():
    if "messages" not in st.session_state:
        st.session_state.messages = []
    if "agent_executor" not in st.session_state:
        st.session_state.agent_executor = None
    if "agent_memory" not in st.session_state:
        st.session_state.agent_memory = None
    if "current_jobs" not in st.session_state:
        st.session_state.current_jobs = []
    if "api_key_set" not in st.session_state:
        st.session_state.api_key_set = bool(os.getenv("GOOGLE_API_KEY"))

init_session()

# ---------------------------------------------------------------------------
# Load agent (cached per session)
# ---------------------------------------------------------------------------
def load_agent():
    if st.session_state.agent_executor is None:
        try:
            from agent import build_agent
            exec_, mem = build_agent(st.session_state.agent_memory)
            st.session_state.agent_executor = exec_
            st.session_state.agent_memory = mem
        except EnvironmentError as e:
            return str(e)
        except Exception as e:
            return f"Failed to load agent: {e}"
    return None

# ---------------------------------------------------------------------------
# Render a job card (HTML)
# ---------------------------------------------------------------------------
def render_job_card(job: dict, idx: int):
    wfh_badge = '<span class="badge badge-green">๐Ÿ  WFH</span>' if job.get("wfh") else ""
    salary = job.get("salary", "Not disclosed")
    if salary and "LPA" not in salary.upper() and salary != "Not disclosed":
        salary_disp = salary
    else:
        salary_disp = salary

    card_html = f"""
    <div class="job-card">
        <div class="job-title">{job.get('title', 'N/A')}</div>
        <div class="job-company">๐Ÿข {job.get('company', 'N/A')}</div>
        <div class="job-meta">
            <span class="badge badge-blue">๐Ÿ“ {job.get('location', 'N/A')}</span>
            <span class="badge badge-purple">๐Ÿ’ฐ {salary_disp}</span>
            <span class="badge">๐Ÿ•’ {job.get('experience', 'N/A')}</span>
            {wfh_badge}
        </div>
        <div style="color:var(--text-muted); font-size:0.9rem; margin-top:1rem; line-height:1.5;">
            {truncate(job.get('description', ''), 200)}
        </div>
    </div>
    """
    st.markdown(card_html, unsafe_allow_html=True)
    col_a, col_b, _ = st.columns([1, 1, 4])
    with col_a:
        if st.button("๐Ÿ’พ Save", key=f"save_{idx}_{job.get('title','')}"):
            ok = db.save_job(job)
            st.toast("โœ… Job saved!" if ok else "โš ๏ธ Already saved or error.")
    with col_b:
        st.link_button("๐Ÿ”— Apply", url=job.get("url", "#"))

# ---------------------------------------------------------------------------
# Sidebar
# ---------------------------------------------------------------------------
def render_sidebar():
    with st.sidebar:
        st.markdown("## ๐Ÿค– CareerBot")
        st.markdown("*AI Job Search ยท Indian Market*")
        st.divider()

        # API Key section
        st.markdown("### ๐Ÿ”‘ API Key")
        if not st.session_state.api_key_set:
            api_key_input = st.text_input(
                "Google Gemini API Key",
                type="password",
                placeholder="AIzaSy...",
                help="Get free key at aistudio.google.com",
            )
            if api_key_input:
                os.environ["GOOGLE_API_KEY"] = api_key_input
                st.session_state.api_key_set = True
                st.session_state.agent_executor = None  # reset to rebuild
                st.success("โœ… Key set!")
                st.rerun()
            st.caption("[Get free Gemini API key โ†’](https://aistudio.google.com)")
        else:
            st.success("โœ… API key configured")
            if st.button("๐Ÿ”„ Change key"):
                os.environ["GOOGLE_API_KEY"] = ""
                st.session_state.api_key_set = False
                st.session_state.agent_executor = None
                st.rerun()

        st.divider()

        # Search Filters
        st.markdown("### ๐Ÿ” Search Filters")
        st.caption("These filters are sent to the agent automatically.")

        location = st.selectbox("๐Ÿ“ Location", ALL_CITIES, index=0)
        experience = st.selectbox("๐ŸŽ“ Experience", EXPERIENCE_LEVELS, index=0)
        salary = st.selectbox("๐Ÿ’ฐ Salary Range", SALARY_RANGES, index=0)
        domain = st.selectbox("๐Ÿ’ผ Domain / Role", ["Any"] + JOB_DOMAINS, index=0)
        wfh = st.checkbox("๐Ÿ  Work From Home only", value=False)
        notice = st.selectbox("๐Ÿ“… Max Notice Period", ["Any"] + NOTICE_PERIODS, index=0)

        st.divider()

        # Quick action buttons
        st.markdown("### โšก Quick Searches")
        quick_searches = [
            "Python developer jobs in Bangalore",
            "Data Science jobs 10+ LPA",
            "Fresher IT jobs Mumbai",
            "WFH jobs 6โ€“10 LPA",
            "Product Manager Bengaluru",
        ]
        for qs in quick_searches:
            if st.button(qs, use_container_width=True, key=f"qs_{qs}"):
                st.session_state["_quick_query"] = qs

        st.divider()
        st.markdown("### ๐Ÿ“Š Your Activity")
        saved = db.get_saved_jobs()
        history = db.get_search_history(5)

        col1, col2 = st.columns(2)
        with col1:
            st.markdown(
                f'<div class="metric-box"><div class="metric-val">{len(saved)}</div>'
                f'<div class="metric-label">Saved</div></div>',
                unsafe_allow_html=True,
            )
        with col2:
            st.markdown(
                f'<div class="metric-box"><div class="metric-val">{len(history)}</div>'
                f'<div class="metric-label">History</div></div>',
                unsafe_allow_html=True,
            )

    return {
        "location": location,
        "experience": experience,
        "salary": salary,
        "domain": domain,
        "wfh": wfh,
        "notice": notice,
    }

# ---------------------------------------------------------------------------
# Build enriched query from filters
# ---------------------------------------------------------------------------
def build_query(user_input: str, filters: dict) -> str:
    parts = [user_input]
    if filters["location"] != "Any / Remote":
        parts.append(f"in {filters['location']}")
    if filters["experience"] != "Fresher (0 yrs)":
        parts.append(f"with {filters['experience']} experience")
    if filters["salary"] != "Any":
        parts.append(f"paying {filters['salary']}")
    if filters["wfh"]:
        parts.append("work from home")
    if filters["domain"] != "Any":
        parts.append(f"in {filters['domain']} domain")
    return " ".join(parts)

# ---------------------------------------------------------------------------
# Tab: Chat
# ---------------------------------------------------------------------------
def tab_chat(filters: dict):
    st.markdown(
        '<div class="main-header"><h1>๐Ÿค– CareerBot</h1>'
        '<p>Your AI-powered Indian Job Search Assistant</p></div>',
        unsafe_allow_html=True,
    )
    st.divider()

    # Check API key
    if not st.session_state.api_key_set:
        st.warning("โš ๏ธ Please enter your **Google Gemini API key** in the sidebar to start chatting.")
        st.info("Get a **free** Gemini API key at [aistudio.google.com](https://aistudio.google.com)")
        return

    # Load agent
    err = load_agent()
    if err:
        st.error(f"โŒ {err}")
        return

    # Render chat history
    chat_container = st.container()
    with chat_container:
        if not st.session_state.messages:
            st.markdown(
                '<div class="chat-bot">๐Ÿš€ <strong>Welcome to CareerBot!</strong><br><br>'
                'I\'m your high-performance AI recruiter dedicated to the <strong>Indian market</strong>. How can I help you level up today?<br><br>'
                'โ€ข <strong>Smart Search:</strong> Find roles by city, CTC (LPA), or WFH.<br>'
                'โ€ข <strong>Company Intel:</strong> Get the inside scoop on culture & rounds.<br>'
                'โ€ข <strong>Strategic Advice:</strong> Tailored tips for the Indian landscape.<br><br>'
                '<em>Try: "Find Senior React roles in Bangalore with 5+ years experience"</em></div>',
                unsafe_allow_html=True,
            )
        for msg in st.session_state.messages:
            if msg["role"] == "user":
                st.markdown(
                    f'<div class="chat-user">๐Ÿง‘ {msg["content"]}</div>',
                    unsafe_allow_html=True,
                )
            else:
                st.markdown(
                    f'<div class="chat-bot">๐Ÿค– {msg["content"]}</div>',
                    unsafe_allow_html=True,
                )

    # Handle quick search buttons from sidebar
    quick_query = st.session_state.pop("_quick_query", None)

    # Chat input
    user_input = st.chat_input("Ask about jobs, companies, salaries in Indiaโ€ฆ") or quick_query
    if user_input:
        # Enrich with sidebar filters
        full_query = build_query(user_input, filters)

        # Show user message
        st.session_state.messages.append({"role": "user", "content": user_input})

        with st.spinner("๐Ÿ” Searching the Indian job marketโ€ฆ"):
            from agent import ask_agent_async
            response = asyncio.run(ask_agent_async(st.session_state.agent_executor, full_query, st.session_state.messages))

        st.session_state.messages.append({"role": "assistant", "content": response})

        # Log search
        db.log_search(user_input, filters)

        # Try to parse job results from agent response if JSON is embedded
        # (Agent sometimes returns raw JSON from tool output)
        try:
            if "[{" in response:
                start = response.index("[{")
                end = response.rindex("}]") + 2
                jobs_json = response[start:end]
                st.session_state.current_jobs = json.loads(jobs_json)
            else:
                st.session_state.current_jobs = []
        except Exception:
            st.session_state.current_jobs = []

        st.rerun()

# ---------------------------------------------------------------------------
# Tab: Job Listings (direct search, no agent overhead)
# ---------------------------------------------------------------------------
def tab_jobs(filters: dict):
    st.markdown("## ๐Ÿ’ผ Browse Job Listings")
    st.caption("Parallel AI Search across multiple APIs (Adzuna + Jooble Aggregator) for max coverage.")

    col_q, col_btn = st.columns([4, 1])
    with col_q:
        keyword = st.text_input(
            "Search keywords",
            placeholder="e.g. Python, Data Scientist, Product Manager",
            label_visibility="collapsed",
        )
    with col_btn:
        search_clicked = st.button("๐Ÿ” Search", use_container_width=True)

    if search_clicked or keyword:
        # Load agent if not loaded
        err = load_agent()
        if err:
            st.error(f"โŒ {err}")
            return

        query_payload = json.dumps({
            "query": keyword or "software engineer",
            "location": filters["location"],
            "experience": filters["experience"],
            "salary": filters["salary"],
            "wfh": filters["wfh"],
        })
        
        agent_query = f"I am using the Job Listings tab. Please find jobs with these exact parameters and return the results as JSON: {query_payload}"

        with st.spinner("Agent is searching the marketโ€ฆ"):
            from agent import ask_agent_async
            response = asyncio.run(ask_agent_async(st.session_state.agent_executor, agent_query))

        try:
            # Try to extract JSON from agent response
            if "[{" in response:
                start = response.index("[{")
                end = response.rindex("}]") + 2
                jobs_json = response[start:end]
                jobs = json.loads(jobs_json)
            else:
                jobs = []
        except Exception:
            jobs = []

        if not jobs:
            st.info("CareerBot couldn't find matches for those specifics. Try broader keywords.")
            if response:
                with st.expander("Agent Reasoning"):
                    st.write(response)
            return

        st.markdown(f"### Found **{len(jobs)}** matching jobs")
        st.divider()
        for i, job in enumerate(jobs):
            render_job_card(job, i)

        # Log
        db.log_search(keyword, filters, len(jobs))

    else:
        st.markdown("### ๐Ÿ”ฅ Trending Indian Job Listings")
        st.caption("AI Agent is fetching live trending data dynamically...")
        
        # Load agent if not loaded
        err = load_agent()
        if err: return

        agent_query = "Fetch 6 high-quality 'Software Engineer' jobs in India as JSON."
        
        with st.spinner("Agent is fetching featured jobsโ€ฆ"):
            from agent import ask_agent_async
            response = asyncio.run(ask_agent_async(st.session_state.agent_executor, agent_query))
            
        try:
            if "[{" in response:
                start = response.index("[{")
                end = response.rindex("}]") + 2
                jobs = json.loads(response[start:end])
            else:
                jobs = []
        except Exception:
            jobs = []
            
        for i, job in enumerate(jobs[:6]):
            render_job_card(job, i)
        
        if not jobs:
            st.info("No jobs found for this exact query. Try a different search above, or wait a minute if you just hit the API speed limit!")

# ---------------------------------------------------------------------------
# Tab: Saved Jobs
# ---------------------------------------------------------------------------
def tab_saved():
    st.markdown("## ๐Ÿ’พ Saved Jobs")

    saved = db.get_saved_jobs()
    if not saved:
        st.info("๐Ÿ“ญ No saved jobs yet. Browse the **Job Listings** tab and click **Save** to bookmark jobs.")
        return

    st.markdown(f"You have saved **{len(saved)}** jobs.")
    st.divider()
    for job in saved:
        with st.expander(f"๐Ÿ“Œ {job['title']} @ {job['company']}", expanded=False):
            col1, col2, col3 = st.columns(3)
            col1.metric("Location", job.get("location", "N/A"))
            col2.metric("Salary", job.get("salary", "N/A"))
            col3.metric("Experience", job.get("experience", "N/A"))
            if job.get("description"):
                st.caption(truncate(job["description"], 300))
            if job.get("url"):
                st.link_button("๐Ÿ”— Apply Now", url=job["url"])

            if st.button("๐Ÿ—‘๏ธ Remove", key=f"del_{job['id']}"):
                db.delete_saved_job(job["id"])
                st.success("Removed.")
                st.rerun()

# ---------------------------------------------------------------------------
# Tab: Company Research
# ---------------------------------------------------------------------------
def tab_company():
    st.markdown("## ๐Ÿข Company Research")
    st.caption("AI-powered deep research into Indian companies โ€“ culture, salaries, and interview tips.")

    selected = st.text_input("Enter a company name (e.g., TCS, Flipkart, Zerodha)")

    if selected:
        # Load agent if not loaded
        err = load_agent()
        if err:
            st.error(f"โŒ {err}")
            return

        agent_query = f"Research the company '{selected}' in the Indian market and return the full details as JSON."

        with st.spinner(f"Agent is researching {selected}โ€ฆ"):
            from agent import ask_agent_async
            response = asyncio.run(ask_agent_async(st.session_state.agent_executor, agent_query))
            
        try:
            # Extract JSON from agent response
            if "{" in response:
                start = response.index("{")
                end = response.rindex("}") + 1
                info_json = response[start:end]
                info = json.loads(info_json)
            else:
                info = {"message": "CareerBot couldn't find structured data for this company."}
        except Exception:
            info = {"message": "Error parsing company data from agent reasoning."}

        if "message" in info:
            st.warning(info["message"])
            with st.expander("Agent Reasoning"):
                st.write(response)
            return

        st.markdown(f"### {info.get('name', selected)}")
        st.caption(f"{info.get('type', '')} ยท Founded {info.get('founded', 'N/A')} ยท HQ: {info.get('hq', 'N/A')}")
        st.divider()

        cols = st.columns(4)
        with cols[0]:
            st.markdown(f'<div class="metric-box"><div class="metric-val" style="font-size:1.2rem;">{info.get("employees", "N/A")}</div><div class="metric-label">Employees</div></div>', unsafe_allow_html=True)
        with cols[1]:
            st.markdown(f'<div class="metric-box"><div class="metric-val" style="font-size:1.2rem;">{info.get("revenue", info.get("funding", "N/A"))}</div><div class="metric-label">Revenue/Funding</div></div>', unsafe_allow_html=True)
        with cols[2]:
            st.markdown(f'<div class="metric-box"><div class="metric-val" style="font-size:1.2rem;">{info.get("rating", "N/A")} โ˜…</div><div class="metric-label">Rating</div></div>', unsafe_allow_html=True)
        with cols[3]:
            st.markdown(f'<div class="metric-box"><div class="metric-val" style="font-size:1.2rem;">{info.get("ceo", "N/A")}</div><div class="metric-label">CEO</div></div>', unsafe_allow_html=True)

        st.divider()
        col_a, col_b = st.columns(2)
        with col_a:
            st.markdown("#### ๐Ÿ’ฐ Salary Range")
            st.info(info.get("salary_range", "N/A"))
            st.markdown("#### โฐ Notice Period")
            st.write(info.get("notice_period", "N/A"))
            st.markdown("#### ๐Ÿ  WFH Policy")
            st.write(info.get("wfh_policy", "N/A"))
        with col_b:
            st.markdown("#### โœ… Pros")
            for p in info.get("pros", []):
                st.success(f"โœ“ {p}")
            st.markdown("#### โš ๏ธ Cons")
            for c in info.get("cons", []):
                st.warning(f"โ€ข {c}")

        st.divider()
        st.markdown("#### ๐ŸŽฏ Interview Process")
        st.write(info.get("interview", "N/A"))
        st.markdown("#### โš–๏ธ Work-Life Balance")
        st.write(info.get("work_life", "N/A"))
        if info.get("website"):
            st.link_button("๐ŸŒ Visit Careers Page", url=info["website"])

# ---------------------------------------------------------------------------
# Tab: LinkedIn Profile Analyzer
# ---------------------------------------------------------------------------
def tab_linkedin():
    st.markdown("## ๐Ÿ‘ค LinkedIn Profile Analyzer")
    st.caption("AI-powered summary of any LinkedIn profile using RapidAPI's extractor tool.")

    selected_url = st.text_input("Enter a LinkedIn Profile URL (e.g., https://www.linkedin.com/in/satyanadella)")

    if selected_url:
        err = load_agent()
        if err:
            st.error(f"โŒ {err}")
            return

        agent_query = (
            f"Please extract the LinkedIn profile context for '{selected_url}' and act as an expert career coach. "
            "Using the extracted data (experience, education, certifications, projects), provide a deep profile analysis including: "
            "1. **Executive Summary** of their professional identity. "
            "2. **Plus Points** (Core strengths & unique skills). "
            "3. **Minus Points / Gaps** (Areas for improvement or missing elements). "
            "4. **Best Job Roles** (3-4 specific career trajectory recommendations). "
            "5. **Where to Apply** (Types of companies or specific Indian companies that fit this profile). "
            "Make sure to append the RAW JSON API data at the bottom of your response."
        )

        with st.spinner("Agent is scanning LinkedIn profileโ€ฆ"):
            from agent import ask_agent_async
            response = asyncio.run(ask_agent_async(st.session_state.agent_executor, agent_query))
            
        st.markdown(response)

# ---------------------------------------------------------------------------
# Tab: About / How to Use
# ---------------------------------------------------------------------------
def tab_about():
    st.markdown("""
## ๐Ÿค– About CareerBot

CareerBot is an **AI-powered job search assistant** built for the **Indian job market** as part of a college AI agent project (Track A โ€“ Week 1 milestone).

---

### ๐Ÿ› ๏ธ Tech Stack
| Layer | Technology |
|-------|------------|
| **Frontend** | Streamlit |
| **AI Agent** | LangChain + Google Gemini 2.5 Flash |
| **Job Data** | Indeed India scraper + curated mock dataset |
| **Database** | SQLite (saved jobs & search history) |
| **Language** | Python 3.11+ |

---

### ๐Ÿ‡ฎ๐Ÿ‡ณ Indian Market Features
- **Salary in LPA** (Lakhs Per Annum) format
- **Metro + Tier-2 city** filtering (Bangalore, Mumbai, Hyderabad, Pune, Delhi/NCRโ€ฆ)
- **Notice period** awareness (Immediate / 15 / 30 / 60 / 90 days)
- **WFH / Hybrid** preference filtering
- **Fresher-friendly** search (0 years experience)
- Company database: **TCS, Infosys, Wipro, Flipkart, Swiggy, Zomato, Razorpay, Paytm, HCL**

---

### ๐Ÿš€ How to Use
1. **Enter your Gemini API key** in the sidebar (free at [aistudio.google.com](https://aistudio.google.com))
2. **Set filters** โ€“ location, experience, salary range, WFH preference
3. **Chat** with CareerBot or use the **Job Listings** tab for direct search
4. **Save** interesting jobs for later
5. **Research** companies before applying

---

### ๐Ÿ“ Project Structure
```
capbl/
โ”œโ”€โ”€ app.py          โ† You are here (Streamlit UI)
โ”œโ”€โ”€ agent.py        โ† LangChain + Gemini agent
โ”œโ”€โ”€ database.py     โ† SQLite persistence
โ”œโ”€โ”€ utils.py        โ† Indian market constants & helpers
โ”œโ”€โ”€ tools/
โ”‚   โ”œโ”€โ”€ job_search.py   โ† Indeed scraper + mock data
โ”‚   โ””โ”€โ”€ company_info.py โ† Company knowledge base
โ””โ”€โ”€ requirements.txt
```

---
*Built for Week 1โ€“2 milestone of the Job Search AI Agent project.*
""")

# ---------------------------------------------------------------------------
# Tab: Market Intelligence
# ---------------------------------------------------------------------------
def tab_intelligence():
    st.markdown("## ๐Ÿ“ˆ Market Intelligence")
    st.caption("AI Agent analysis of live hiring trends across Indian tech hubs.")

    city = st.selectbox("Select City", ["Bangalore", "Mumbai", "Hyderabad", "Pune", "Delhi/NCR", "Chennai"])
    
    if st.button("๐Ÿ” Analyze Market", use_container_width=True):
        err = load_agent()
        if err: return
        
        agent_query = f"Analysis of current hiring trends in {city} for tech roles."
        
        with st.spinner(f"Agent is analyzing {city} marketโ€ฆ"):
            from agent import ask_agent_async
            response = asyncio.run(ask_agent_async(st.session_state.agent_executor, agent_query))
            
        st.markdown(f"### Reasoning for {city}")
        st.info(response)

# ---------------------------------------------------------------------------
# Main app layout
# ---------------------------------------------------------------------------
def main():
    filters = render_sidebar()

    tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs([
        "๐Ÿ’ฌ Chat",
        "๐Ÿ’ผ Job Listings",
        "๐Ÿ’พ Saved Jobs",
        "๐Ÿข Company",
        "๐Ÿ‘ค LinkedIn Profile",
        "๐Ÿ“ˆ Intelligence",
        "โ„น๏ธ About",
    ])

    with tab1:
        tab_chat(filters)
    with tab2:
        tab_jobs(filters)
    with tab3:
        tab_saved()
    with tab4:
        tab_company()
    with tab5:
        tab_linkedin()
    with tab6:
        tab_intelligence()
    with tab7:
        tab_about()


if __name__ == "__main__":
    main()