#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import urllib.request
import urllib.parse
import json
import datetime
import re
import ssl

REMOTEOK_API_URL = "https://remoteok.com/api"
POST_ENDPOINT = "https://digvera.com/clientradar/save_project.php"

# ✅ دریافت داده‌ها از RemoteOK
def fetch_remoteok_jobs():
    context = ssl._create_unverified_context()
    try:
        with urllib.request.urlopen(REMOTEOK_API_URL, context=context) as response:
            return json.loads(response.read().decode())
    except Exception as e:
        print("❌ خطا در دریافت اطلاعات از RemoteOK:", e)
        return []

# ✅ پاک‌سازی توضیحات پروژه
def clean_description(text):
    if not text:
        return ""
    text = re.sub(r"<[^>]+>", " ", text)             # حذف تگ‌های HTML
    text = re.sub(r"&[a-zA-Z]+;", " ", text)         # حذف HTML entities
    text = re.sub(r"http[s]?://\S+", " ", text)      # حذف URLها
    text = re.sub(r"\s+", " ", text).strip()         # حذف فاصله‌های اضافی
    return text[:250]  # محدود به ۲۵۰ کاراکتر

# ✅ فیلتر پروژه‌های ۲۴ ساعت گذشته
def filter_recent_projects(raw_jobs):
    filtered = []
    for job in raw_jobs:
        if not isinstance(job, dict):
            continue
        date_str = job.get("date", "")
        try:
            job_time = datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z")
        except:
            continue

        now = datetime.datetime.now(datetime.timezone.utc)
        if (now - job_time).total_seconds() > 86400:
            continue

        # پاک‌سازی و آماده‌سازی داده‌ها
        project = {
            "title": job.get("position", "").strip(),
            "description": clean_description(job.get("description", "")),
            "budget": "Not specified",  # RemoteOK بودجه ندارد
            "link": job.get("url", ""),
            "company": job.get("company", ""),
            "source": "remoteok"
        }

        if project["title"] and project["link"]:
            filtered.append(project)
    return filtered

# ✅ ارسال داده‌ها به سرور
def send_to_server(projects):
    if not projects:
        print("⚠️ هیچ پروژه‌ای برای ارسال وجود ندارد.")
        return

    headers = {
        "Content-Type": "application/json"
    }

    try:
        data = json.dumps(projects).encode("utf-8")
        req = urllib.request.Request(POST_ENDPOINT, data=data, headers=headers)
        context = ssl._create_unverified_context()
        with urllib.request.urlopen(req, context=context) as response:
            resp_data = response.read().decode()
            print("✅ داده‌ها با موفقیت ارسال شدند.")
            print("📩 پاسخ سرور:", resp_data)
    except Exception as e:
        print("❌ خطا در ارسال به سرور:", e)

# ✅ اجرای کامل راداربات
def main():
    print("🚀 اجرای RadarBot شروع شد...")
    raw_jobs = fetch_remoteok_jobs()
    projects = filter_recent_projects(raw_jobs)
    send_to_server(projects)
    print("✅ RadarBot پایان یافت.")

if __name__ == "__main__":
    main()



