# -*- coding: utf-8 -*-

import os
from ftplib import FTP

from config import (
    CAFE24_FTP_HOST,
    CAFE24_FTP_PORT,
    CAFE24_FTP_USER,
    CAFE24_FTP_PASS,
    CAFE24_FTP_PASSIVE,
    CAFE24_REMOTE_BASE_DIR,
    CAFE24_IMAGE_BASE_URL,
)


def ftp_makedirs(ftp, remote_dir):
    parts = remote_dir.strip("/").split("/")
    path = ""

    for part in parts:
        if not part:
            continue

        path += "/" + part

        try:
            ftp.mkd(path)
        except Exception:
            pass


def upload_file_to_cafe24(local_path, article_no, image_category, file_name):
    remote_dir = (
        CAFE24_REMOTE_BASE_DIR.strip("/")
        + "/"
        + str(article_no).strip()
        + "/"
        + str(image_category).strip()
    )

    remote_dir = "/" + remote_dir.strip("/")
    remote_path = remote_dir + "/" + file_name

    ftp = FTP()
    ftp.connect(CAFE24_FTP_HOST, CAFE24_FTP_PORT, timeout=30)
    ftp.login(CAFE24_FTP_USER, CAFE24_FTP_PASS)
    ftp.set_pasv(CAFE24_FTP_PASSIVE)

    try:
        ftp_makedirs(ftp, remote_dir)

        with open(local_path, "rb") as f:
            ftp.storbinary(f"STOR {remote_path}", f)

    finally:
        try:
            ftp.quit()
        except Exception:
            pass

    public_url = (
        CAFE24_IMAGE_BASE_URL.rstrip("/")
        + "/"
        + str(article_no).strip()
        + "/"
        + str(image_category).strip()
        + "/"
        + file_name
    )

    return public_url