import requests
import os
from urllib.parse import urlparse
import paramiko
from ftplib import FTP
# === STEP 1: TRIGGER BOTH LESA SERVICES ===

url = "https://ebait.biz/ebait_manager/inventory_processor_live2.php"
lesa_services = ["LESA INVENTORY", "lesa photos", "zendesk_sheparselect", "MotoHunt", "Shiftly-Auto", "Chroma IMS", "covideo"]

for service in lesa_services:
    print(f"🚀 Sending POST request for: {service}")
    try:
        response = requests.post(url, data={"vehicle_service": service})
        print("Status Code:", response.status_code)
        # print("Response:\n", response.text)
        if response.status_code != 200:
            print(f"❌ {service} service failed.")
            exit(1)
    except requests.exceptions.RequestException as e:
        print(f"❌ Request for {service} failed:", e)
        exit(1)

FTP_SERVERS = [
    {
        "host": "34.198.197.102",
        "port": 21,
        "username": "chromacars_user",
        "password": "M24g5CisZWv!",
        "remote_path": "/uploads",

        "files": [
            {
                "name": "covideo.csv",
                "url": "https://ebait.biz/ebait_manager/inventory/covideo.csv"
            },
        ]
    },

    {
        "host": "ftp.truimagesauto.com",
        "port": 21,
        "username": "Chromacars",
        "password": "Hyperlook",
        "remote_path": "/",

        "files": [
            {
                "name": "tru_nalleygmc.csv",
                "url": "https://ebait.biz/ebait_manager/inventory/tru_nalleygmc.csv"
            },
            {
                "name": "tru_KiaofChattanooga.csv",
                "url": "https://ebait.biz/ebait_manager/inventory/tru_KiaofChattanooga.csv"
            },
            {
                "name": "tru_KiaofCleveland.csv",
                "url": "https://ebait.biz/ebait_manager/inventory/tru_KiaofCleveland.csv"
            },
            {
                            "name": "tru_hughwhitehonda.csv",
                            "url": "https://ebait.biz/ebait_manager/inventory/tru_hughwhitehonda.csv"
            },
            {
                                        "name": "nalleyhonda.csv",
                                        "url": "https://ebait.biz/ebait_manager/inventory/tru_nalleyhonda.csv"
            },
        ]
    },
]
import os
import requests
from ftplib import FTP

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DOWNLOAD_FOLDER = os.path.join(BASE_DIR, "downloads")
os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)

# -----------------------------
# DOWNLOAD
# -----------------------------

print("\n⬇ Downloading files...\n")

for server in FTP_SERVERS:

    for file in server["files"]:

        local_path = os.path.join(DOWNLOAD_FOLDER, file["name"])

        try:
            r = requests.get(file["url"], timeout=60)
            r.raise_for_status()

            with open(local_path, "wb") as f:
                f.write(r.content)

            print(f"✅ Downloaded {file['name']}")

        except Exception as e:
            print(f"❌ Failed downloading {file['name']}: {e}")

# -----------------------------
# UPLOAD
# -----------------------------

print("\n🚀 Uploading...\n")

for server in FTP_SERVERS:

    print(f"\nConnecting to {server['host']}...")

    try:
        ftp = FTP()
        ftp.connect(server["host"], server["port"], timeout=30)
        ftp.login(server["username"], server["password"])
        ftp.set_pasv(True)
        ftp.cwd(server["remote_path"])

        print("✅ Connected")

        for file in server["files"]:

            local_path = os.path.join(DOWNLOAD_FOLDER, file["name"])

            if not os.path.exists(local_path):
                print(f"⚠ Missing {file['name']}")
                continue

            with open(local_path, "rb") as f:
                ftp.storbinary(f"STOR {file['name']}", f)

            print(f"✅ Uploaded {file['name']}")

        ftp.quit()

    except Exception as e:
        print(f"❌ FTP Error ({server['host']}): {e}")

# -----------------------------
# DELETE
# -----------------------------

print("\n🧹 Cleaning up...\n")

for server in FTP_SERVERS:

    for file in server["files"]:

        local_path = os.path.join(DOWNLOAD_FOLDER, file["name"])

        if os.path.exists(local_path):
            os.remove(local_path)
            print(f"🗑 Deleted {file['name']}")

print("\n✅ Done.")