from datetime import datetime
import os
from jobspy import scrape_jobs
import pandas as pd

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")
os.makedirs(DATA_DIR, exist_ok=True)

# Optional: Add your proxies here to prevent LinkedIn/Glassdoor IP blocks on shared hosting.
# Format: ["user:pass@host:port", "host:port"]
# Leave as an empty list [] to run without proxies using your server IP.
PROXIES = [
    # "username:password@://smartproxy.com",
    # "123.45.67.89:8080",
]

ENGLISH_COUNTRIES = [
    {
        "country_indeed": "USA",
        "location": "United States",
        "sites": ["indeed", "linkedin", "glassdoor", "zip_recruiter"],
    },
    {
        "country_indeed": "UK",
        "location": "United Kingdom",
        "sites": ["indeed", "linkedin", "glassdoor"],
    },
    {
        "country_indeed": "Canada",
        "location": "Canada",
        "sites": ["indeed", "linkedin", "glassdoor", "zip_recruiter"],
    },
    {
        "country_indeed": "Ireland",
        "location": "Ireland",
        "sites": ["indeed", "linkedin", "glassdoor"],
    },
    {
        "country_indeed": "Australia",
        "location": "Australia",
        "sites": ["indeed", "linkedin", "glassdoor", "seek"],
    },
    {
        "country_indeed": "New Zealand",
        "location": "New Zealand",
        "sites": ["indeed", "linkedin", "seek"],
    },
]


def run_english_scraper(results_per_country=15):
    all_jobs = []

    for target in ENGLISH_COUNTRIES:
        try:
            scrape_params = {
                "site_name": target["sites"],
                "location": target["location"],
                "country_indeed": target["country_indeed"],
                "is_remote": True,
                "results_wanted": results_per_country,
            }

            # Attach proxies only if the PROXIES list is not empty
            if PROXIES:
                scrape_params["proxies"] = PROXIES

            jobs = scrape_jobs(**scrape_params)

            if not jobs.empty:
                jobs["target_country"] = target["country_indeed"]
                all_jobs.append(jobs)

        except Exception as e:
            print(f"Error scraping {target['country_indeed']}: {e}")

    if all_jobs:
        final_df = pd.concat(all_jobs, ignore_index=True)
        if "job_url" in final_df.columns:
            final_df.drop_duplicates(subset=["job_url"], inplace=True)

        today_str = datetime.now().strftime("%Y-%m-%d")
        filename = f"english_remote_jobs_{today_str}.csv"
        csv_path = os.path.join(DATA_DIR, filename)

        final_df.to_csv(csv_path, index=False, encoding="utf-8-sig")
        return True, f"Saved {len(final_df)} English remote jobs to {filename}"

    return False, "No English remote jobs found or rate-limited."


if __name__ == "__main__":
    success, msg = run_english_scraper()
    print(msg)
