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 
 
 
 
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
import sys
import os, sys, json, io, zipfile
import json
import requests
from dotenv import load_dotenv
from shiny import reactive, render, ui

# Access code/context.py

from context import get_all_candidates
from llm_connect import get_response

from datetime import datetime
from fpdf import FPDF
from PyPDF2 import PdfReader
import markdown

# Load Calendly token
load_dotenv()
CALENDLY_API_KEY = os.getenv('CALENDLY_API_KEY')
if not CALENDLY_API_KEY:
    raise RuntimeError("❌ CALENDLY_API_KEY not set.")

HEADERS = {
    'Authorization': f"Bearer {CALENDLY_API_KEY}",
    'Content-Type': 'application/json'
}

_event_url_cache = None

def get_user_uri():
    response = requests.get("https://api.calendly.com/users/me", headers=HEADERS, timeout=5)
    response.raise_for_status()
    return response.json()['resource']['uri']

def get_event_type_link(user_uri):
    response = requests.get(f"https://api.calendly.com/event_types?user={user_uri}", headers=HEADERS, timeout=5)
    response.raise_for_status()
    return response.json()['collection'][0]['scheduling_url']

def schedule_interview(name, email):
    global _event_url_cache
    if _event_url_cache is None:
        user_uri = get_user_uri()
        _event_url_cache = get_event_type_link(user_uri)
    return f"{_event_url_cache}?name={name.replace(' ', '+')}&email={email}"


def draft_invite_email_with_llm(name, email, link, job_data):
    prompt = (
        f"You are a recruiter inviting a candidate to schedule an interview.\n\n"
        f"Candidate Name: {name}\n"
        f"Candidate Email: {email}\n\n"
        f"Job Title: {job_data.get('title', 'Unknown')}\n"
        f"Specialization: {job_data.get('specialization', '')}\n"
        f"Job Description:\n{job_data.get('job_description', '')}\n\n"
        f"Scheduling Link: {link}\n\n"
        f"Write a professional, warm, and concise email inviting the candidate to schedule an interview. "
        f"Include the scheduling link. Return only the email body text. No formatting or extra explanation.\n"
        f"Sign under the company name, DO NOT USE MY NAME"
    )

    return get_response(
        input=prompt,
        template=lambda x: x,
        llm="llama",
        md=False,
        temperature=0.7,
        max_tokens=500,
    )

def export_email_as_pdf(name, email_text):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.set_font("Arial", size=12)
    for line in email_text.strip().split("\n"):
        pdf.multi_cell(0, 10, line)
    output_dir = os.path.join(os.path.dirname(__file__), "emails")
    os.makedirs(output_dir, exist_ok=True)
    filename = os.path.join(output_dir, f"{name.replace(' ', '_')}.pdf")
    pdf.output(filename)
    return filename



# === MAIN SHINY SERVER FUNCTION ===
def server(input, output, session):
    print("βœ… Entered interview scheduler server()")

    if not hasattr(session, "_memo"):
        session._memo = {}  # πŸ›  manually initialize in-memory store

    @reactive.Calc
    def job_options():
        raw_candidates = get_all_candidates()
        job_ids_used = {c.get("job_id") for c in raw_candidates.values() if "job_id" in c}

        path = "/tmp/data/context.json"
        try:
            with open(path, "r") as f:
                full = json.load(f)
                all_jobs = full.get("jobs", {})
                session._memo["all_jobs"] = all_jobs
                session._memo["all_candidates"] = full.get("candidates", {})

            # Build job_id: label mapping only for jobs with candidates
            job_choices = {
                job_id: f"{job_data.get('title', 'Untitled')} ({job_id[:8]})"
                for job_id, job_data in all_jobs.items()
                if job_id in job_ids_used
            }

            print(f"πŸ“Š Loaded {len(job_choices)} job IDs with candidates")
            return job_choices
        except Exception as e:
            print("❌ Failed to load job/candidate context:", e)
            return {}


    @output
    @render.ui
    def name_selector():
        job_ids = job_options()
        if not job_ids:
            return ui.p("No jobs available.")
        return ui.div(
            ui.input_select("selected_job", "Select Job ID", choices=job_ids),
            ui.output_ui("candidate_checkbox")
        )

    @output
    @render.ui
    def candidate_checkbox():
        job_id = input.selected_job()
        if not job_id:
            return ui.p("Select a job to view candidates.")

        candidates = session._memo.get("all_candidates", {})
        filtered = [
            {
                "label": f"{c['Name']} ({c['Email']})",
                "name": c["Name"],
                "email": c["Email"]
            }
            for c in candidates.values()
            if str(c.get("job_id", "")).strip() == str(job_id).strip()
        ]

        session._memo["filtered_candidates"] = filtered

        if not filtered:
            return ui.p("No candidates match this job.")

        return ui.input_checkbox_group(
            "selected_names",
            "Select candidates to schedule",
            choices=[c["label"] for c in filtered]
        )

    @output
    @render.ui
    @reactive.event(input.generate_links)
    def output_links_html():
        selected = input.selected_names()
        if not selected:
            return ui.p("No candidates selected.")

        job_id = input.selected_job()
        session._memo["active_job_id"] = job_id

        job_data = session._memo.get("all_jobs", {}).get(job_id, {})
        candidates = {
            f"{c['name']} ({c['email']})": c
            for c in session._memo.get("filtered_candidates", [])
        }

        results = []
        pdf_paths = []

        for label in selected:
            c = candidates.get(label)
            if not c:
                results.append(ui.p(f"{label}: Not found"))
                continue
            try:
                link = schedule_interview(c['name'], c['email'])
                email_text = draft_invite_email_with_llm(c['name'], c['email'], link, job_data)

                # Sanitize name + timestamp
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                safe_name = f"{c['name'].replace(' ', '_')}_{timestamp}"
                filename = f"{safe_name}.pdf"

                # Correct folder: data/emails/{job_id}/
                output_dir = f"/tmp/data/{job_id}/emails"

                os.makedirs(output_dir, exist_ok=True)

                # Full path to PDF file
                pdf_path = os.path.join(output_dir, filename)

                # Generate PDF
                pdf = FPDF()
                pdf.add_page()
                pdf.set_auto_page_break(auto=True, margin=15)
                pdf.set_font("Arial", size=12)
                for line in email_text.strip().split("\n"):
                    pdf.multi_cell(0, 10, line)
                pdf.output(pdf_path)

                # Store PDF
                pdf_paths.append(pdf_path)

                results.append(
                    ui.HTML(f"<p><b>{c['name']}</b>: <a href='{link}' target='_blank'>πŸ“… Schedule</a> β€” PDF ready</p>")
                )

            except Exception as e:
                results.append(ui.p(f"{c['name']}: ERROR - {e}"))

        session._memo["pdf_paths"] = pdf_paths
        return ui.div(*results)


    @output
    @render.ui
    @reactive.event(input.generate_links)  # πŸ” Trigger update after generate button
    def pdf_selector():
        files = session._memo.get("pdf_paths", [])
        if not files:
            return ui.p("No PDFs to preview.")

        default_pdf = os.path.basename(files[0])
        return ui.input_select(
            "selected_pdf",
            "Preview PDF",
            choices=[os.path.basename(f) for f in files],
            selected=default_pdf
        )


    @output
    @render.ui
    @reactive.Calc
    def pdf_preview():
        selected = input.selected_pdf()
        job_id = session._memo.get("active_job_id", "").strip()

        # βœ… DEBUG: show raw values
        print("πŸ“„ pdf_preview triggered")
        print("πŸ” selected_pdf:", selected)
        print("πŸ“ active_job_id:", job_id)

        if not selected:
            return ui.p("⚠️ No PDF selected.")
        if not job_id:
            return ui.p("⚠️ No active job selected.")

        file_path = f"/tmp/data/{job_id}/emails/{selected}"

        if not os.path.exists(file_path):
            print("❌ File not found on disk.")
            return ui.p(f"❌ PDF not found: {selected}")

        try:
            reader = PdfReader(file_path)
            text = "\n".join([page.extract_text() or "" for page in reader.pages])
            print("βœ… PDF text extracted.")
        except Exception as e:
            print("❌ Exception during PDF read:", e)
            return ui.p(f"❌ Failed to extract PDF text: {e}")

        html = markdown.markdown(text)
        return ui.HTML(f"""
            <div style='padding: 1em; font-family: Georgia, serif; font-size: 1rem; line-height: 1.6;'>
                {html}
            </div>
        """)




    @output
    @render.download(filename="Interview_Emails.zip")
    def download_emails():
        pdf_paths = session._memo.get("pdf_paths", [])
        if not pdf_paths:
            return None  # nothing to download

        job_id = session._memo.get("active_job_id", "").strip()
        zip_path = f"/tmp/data/{job_id}/emails/Interview_Emails.zip"

        if os.path.exists(zip_path):
            os.remove(zip_path)

        with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
            for path in pdf_paths:
                zipf.write(path, arcname=os.path.basename(path))

        return zip_path

    @output
    @render.text
    @reactive.event(input.submit_chat)
    def refined_output():
        user_instruction = input.chat_prompt().strip()
        selected = input.selected_pdf()
        job_id = session._memo.get("active_job_id", "").strip()

        if not selected or not job_id:
            return "⚠️ Select a PDF to edit."

        # Load original text
        pdf_path = f"/tmp/data/{job_id}/emails/{selected}"

        if not os.path.exists(pdf_path):
            return "❌ Could not find the original PDF."

        reader = PdfReader(pdf_path)
        original_text = "\n".join([page.extract_text() or "" for page in reader.pages])

        # Call your LLM with edit prompt
        full_prompt = (
            f"The following is an email invitation for a first round interview at a company:\n\n"
            f"{original_text}\n\n"
            f"User instruction: {user_instruction}\n\n"
            f"Please revise the email accordingly. Return only the revised email."
        )

        try:
            revised = get_response(
                input=full_prompt,
                template=lambda x: x,
                llm="llama",
                md=False,
                temperature=0.6,
                max_tokens=600
            )

            pdf = FPDF()
            pdf.add_page()
            pdf.set_auto_page_break(auto=True, margin=15)
            pdf.set_font("Arial", size=12)
            for line in revised.strip().split("\n"):
                pdf.multi_cell(0, 10, line)
            pdf.output(pdf_path)
            pdf_files = [f for f in os.listdir(f"/tmp/data/{job_id}/emails/") if f.endswith(".pdf")]

            ui.update_select("pdf_selector", choices=pdf_files)
            ui.update_text_area("edit_text", value=revised.strip())
            return revised.strip()
        except Exception as e:
            return f"❌ LLM failed: {e}"
        

    @reactive.effect
    @reactive.event(input.toggle_edit)
    def load_pdf_for_editing():
        selected = input.selected_pdf()
        job_id = session._memo.get("active_job_id", "").strip()
        if not selected or not job_id:
            return

        file_path = f"/tmp/data/{job_id}/emails/{selected}"

        if not os.path.exists(file_path):
            return
        reader = PdfReader(file_path)
        text = "\n".join([page.extract_text() or "" for page in reader.pages])

        ui.update_text_area("edit_text", value=text)



    @reactive.effect
    @reactive.event(input.save_edit)
    def save_edited_pdf():
        selected = input.selected_pdf()
        job_id = session._memo.get("active_job_id", "").strip()
        new_text = input.edit_text().strip()

        if not selected or not job_id or not new_text:
            return

        file_path = f"/tmp/data/{job_id}/emails/{selected}"

        pdf = FPDF()
        pdf.add_page()
        pdf.set_auto_page_break(auto=True, margin=15)
        pdf.set_font("Arial", size=12)
        for line in new_text.splitlines():
            pdf.multi_cell(0, 10, line)
        pdf.output(file_path)

        print(f"βœ… Overwrote PDF: {file_path}")
        pdf_files = [f for f in os.listdir(f"/tmp/data/{job_id}/emails") if f.endswith(".pdf")]
        ui.update_select("pdf_selector", choices=pdf_files)

        session.send_input_message("selected_pdf", {"value": selected})


    @output
    @render.ui
    def edit_ui_block():
        if input.toggle_edit() % 2 == 1:
            return ui.div(
                ui.input_text_area("edit_text", "Edit Email Text:", rows=20),
                ui.input_action_button("save_edit", "πŸ’Ύ Overwrite PDF"),
                style="margin-top: 1em;"
            )
        else:
            return None