# detect_copy.py

import streamlit as st
import google.generativeai as genai
import os
import re
import pandas as pd
import plotly.graph_objects as go
from utils import save_txt, export_pdf, ensure_outputs_folder, save_csv_report

st.set_page_config(page_title="Job Fraud Detector", layout="wide")

# Ensure outputs folder exists
ensure_outputs_folder()

# Set environment key
os.environ["GOOGLE_API_KEY"] = "AIzaSyBasrqxqM8ET9UzdRKAIdowMOXen0qDpnY"
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")

if not GOOGLE_API_KEY:
    st.error("Please set your GOOGLE_API_KEY environment variable.")
    st.stop()

genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel("gemini-2.5-pro")

tab1, tab2, tab3, tab4 = st.tabs(["Home", "AI Tool", "Questionnaire", "About Us"])

with tab1:
    st.header("This program helps determine fraudulent job listings using AI analysis and smart pattern detection.")

with tab2:
    st.title("JobGuard - AI Powered Job Fraud Detector (Powered by Gemini)")
    st.subheader("Job Information")

    job_title = st.text_input("Job Title")
    company_name = st.text_input("Company Name")
    location = st.text_input("Location")
    salary = st.text_input("Salary (if listed)")
    source = st.selectbox(
        "Where did you find this listing?",
        ["Indeed", "LinkedIn", "Company Website", "Referral", "Other"]
    )

    st.header("Paste the job description below")
    inputListing = st.text_area("Paste the job listing below:", height=300)

    # Phrase highlighting
    scammy_phrases = [
        "wire transfer", "Western Union", "send money", "no experience", "quick money",
        "crypto wallet", "urgent start", "bank account", "training fee"
    ]
    flagged = [p for p in scammy_phrases if p.lower() in inputListing.lower()]

    job_metadata = f"""
    Job Title: {job_title or "Not specified"}
    Company: {company_name or "Not specified"}
    Location: {location or "Not specified"}
    Salary: {salary or "Not specified"}
    Source: {source or "Not specified"}
    """

    if st.button("Analyze Listing"):
        if not inputListing.strip():
            st.warning("Please input something into the prompt.")
        else:
            prompt = f"""
            You are going to analyze this job listing to determine if it is fraudulent or not.

            Job Information:
            {job_metadata}

            Job Listing:
            \"\"\"
                {inputListing}
            \"\"\"

            Score the listing based on these:
            - Verdict: Fraudulent / Legitimate / Uncertain
            - Confidence: (0-100)
            - Margin of error: (percentage)
            - Conclusion and explanation: (why this verdict)
            """

            with st.spinner("Analyzing with Gemini..."):
                try:
                    response = model.generate_content(prompt)
                    result = response.text
                    st.success("Analysis Complete.")
                    st.markdown(result)

                    # Save output
                    save_txt(result)
                    export_pdf(result)
                    save_csv_report(result, job_title, company_name, location, salary, source)

                    # Extract metrics (simple parsing)
                    confidence_match = re.search(r"[Cc]onfidence.*?(\d+)", result)
                    error_match = re.search(r"[Mm]argin of error.*?(\d+)", result)
                    verdict_match = re.search(r"[Vv]erdict.*?:\s*\*{0,2}(.*?)(\*|$)", result)


                    conf = float(confidence_match.group(1)) if confidence_match else 0
                    err = float(error_match.group(1)) if error_match else 0
                    verdict = verdict_match.group(1).strip() if verdict_match else "Unknown"

                    st.subheader("📊 AI Verdict Visualization")
                    fig = go.Figure(go.Indicator(
                        mode = "gauge+number+delta",
                        value = conf,
                        domain = {'x': [0, 1], 'y': [0, 1]},
                        title = {'text': f"Confidence Score\nVerdict: {verdict}"},
                        delta = {'reference': 100 - err},
                        gauge = {
                            'axis': {'range': [0, 100]},
                            'bar': {'color': "green" if verdict == "Legitimate" else "red"},
                            'steps': [
                                {'range': [0, 50], 'color': "lightcoral"},
                                {'range': [50, 85], 'color': "gold"},
                                {'range': [85, 100], 'color': "lightgreen"}
                            ],
                        }))
                    st.plotly_chart(fig)

                    st.subheader("Downloads")
                    col1, col2, col3 = st.columns(3)
                    with col1:
                        st.download_button("Download TXT", result, file_name="job_review.txt")
                    with col2:
                        with open("outputs/last_report.pdf", "rb") as f:
                            st.download_button("Download PDF", f, file_name="job_review.pdf")
                    with col3:
                        with open("outputs/last_result.csv", "rb") as f:
                            st.download_button("Download CSV", f, file_name="job_review.csv")

                    if flagged:
                        st.warning(f"⚠️ Scam-related phrases found: {', '.join(flagged)}")

                except Exception as e:
                    st.error(f"Error: {e}")

with tab3:
    st.header("This questionnaire will help determine if a job listing is a scam or not")

    questions = {
        "q1": st.radio("Did the job offer come unsolicited or you didn't apply for it?", ('No', 'Yes')),
        "q2": st.radio("Does the job listing or recruiter use a generic email such as yahoo or gmail?", ('No', 'Yes')),
        "q3": st.radio("Does the company avoid giving you a physical address or phone number?", ('No', 'Yes')),
        "q4": st.radio("Is the job description vague or full of spelling or grammar errors?", ('No', 'Yes')),
        "q5": st.radio("Does the job promise very high pay for little or no experience?", ('No', 'Yes')),
        "q6": st.radio("Is the company unwilling to do a video or an in-person interview?", ('No', 'Yes')),
        "q7": st.radio("Does the job ask you to pay upfront for training or equipment?", ('No', 'Yes')),
        "q8": st.radio("Are you asked to provide your bank account information or Social Security number early in the application process?", ('No', 'Yes')),
        "q9": st.radio("Do they want you to cash in a check and send money to another place?", ('No', 'Yes')),
        "q10": st.radio("Is the company name or branding hard to find online or doesn't have a website?", ('No', 'Yes')),
        "q11": st.radio("Does the company avoid giving details about who the boss or coworkers will be?", ('No', 'Yes')),
        "q12": st.radio("Are they pressuring you into making a decision urgently?", ('No', 'Yes'))
    }

    for key, answer in questions.items():
        if answer == 'Yes':
            st.write("⚠️ Warning signs detected based on question:", key)

with tab4:
    st.header("About Us")
    st.markdown("""
    ### Meet the Team
    We are a dedicated group of undergraduate students from Florida International University (FIU), collaborating on this project as part of our final Capstone experience. With diverse backgrounds in computer science, data analysis, and user experience design, we united around a shared goal: to create a meaningful, real-world application using AI to make the online job market safer for everyone.

    ### Project Goal
    Our mission is to empower job seekers by providing a tool that leverages artificial intelligence to detect fraudulent job postings efficiently and accurately. By combining machine learning with user-friendly design, we aim to reduce the risk of users falling victim to scams — especially students, entry-level applicants, and remote job seekers who are often targeted by fraudulent listings.

    ### Technologies Used
    - Python – Core programming language for model development and backend logic
    - Streamlit – Framework for creating an interactive and responsive web interface
    - Gemini Pro (Google Generative AI) – For advanced natural language understanding and classification
    - Plotly – For creating dynamic, data-driven visualizations
    - FPDF – To generate downloadable reports in PDF format for users

    ### Why It Matters
    The job market is increasingly digital, and with that comes an alarming rise in employment-related scams. These scams not only cost time and money but can also cause serious emotional and reputational harm. By using AI to flag suspicious listings, our tool gives users an extra layer of protection and peace of mind. We believe that everyone deserves a safe, transparent job search and we’re proud to contribute to that mission.

    ### Thank You
    Thank you for exploring our project! Whether you're a student, job seeker, recruiter, or simply curious about the intersection of AI and cybersecurity, we hope you find our tool useful and insightful. Your support and feedback help drive innovation forward.
    """)
