#!/usr/bin/env python3
"""
Upload raportu HTML na serwer FTP (adspro.projectpro.pl).

Użycie:
    python scripts/reports/upload_report_ftp.py --local-dir output/studio-zoe.pl/2026-02/ --remote-path /raporty/studio-zoe/2026-02/
"""

import argparse
import ftplib
import os
import sys
import io
from pathlib import Path

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")

ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(ROOT))
from src.gads_v2.config import load_env

load_env(ROOT / ".env")


def ftp_mkdirs(ftp, path):
    """Create nested directories on FTP server."""
    dirs = path.strip("/").split("/")
    current = ""
    for d in dirs:
        current += f"/{d}"
        try:
            ftp.cwd(current)
        except ftplib.error_perm:
            try:
                ftp.mkd(current)
                print(f"  Utworzono katalog: {current}")
            except ftplib.error_perm:
                pass  # already exists or no permission


def main():
    parser = argparse.ArgumentParser(description="Upload raportu na FTP")
    parser.add_argument("--local-dir", required=True, help="Lokalny folder z raportem")
    parser.add_argument("--remote-path", required=True, help="Sciezka na serwerze (np. /raporty/studio-zoe/2026-02/)")
    args = parser.parse_args()

    host = os.environ["ADSPRO_HOST"]
    user = os.environ["ADSPRO_USERNAME"]
    password = os.environ["ADSPRO_PASSWORD"]
    base_path = os.environ["ADSPRO_REMOTE_PATH"]

    local_dir = Path(args.local_dir)
    if not local_dir.is_absolute():
        local_dir = ROOT / "scripts" / "reports" / local_dir

    if not local_dir.exists():
        print(f"Blad: folder {local_dir} nie istnieje")
        sys.exit(1)

    # Fix Git Bash path mangling on Windows (e.g. /raporty -> C:/Program Files/Git/raporty)
    remote_path = args.remote_path
    if "Program Files/Git" in remote_path or ":" in remote_path:
        # Extract the intended path after the Git prefix
        import re
        match = re.search(r'/raporty/.+', remote_path)
        if match:
            remote_path = match.group(0)
        else:
            remote_path = "/" + remote_path.split("/")[-3] + "/" + remote_path.split("/")[-2] + "/" + remote_path.split("/")[-1]

    remote_full = base_path.rstrip("/") + "/" + remote_path.strip("/")

    print(f"Laczenie z {host}...")

    # Try FTP_TLS first, fallback to plain FTP
    try:
        ftp = ftplib.FTP_TLS(host, timeout=30)
        ftp.login(user, password)
        ftp.prot_p()
        print("  Polaczono (FTP TLS)")
    except Exception:
        ftp = ftplib.FTP(host, timeout=30)
        ftp.login(user, password)
        print("  Polaczono (FTP)")

    ftp.encoding = "utf-8"

    # Create remote directory structure
    print(f"Tworzenie katalogow: {remote_full}")
    ftp_mkdirs(ftp, remote_full)
    ftp.cwd(remote_full)

    # Upload all files
    files_uploaded = 0
    for file_path in local_dir.rglob("*"):
        if file_path.is_file():
            relative = file_path.relative_to(local_dir)
            remote_file = str(relative).replace("\\", "/")

            # Create subdirectories if needed
            if "/" in remote_file:
                subdir = "/".join(remote_file.split("/")[:-1])
                ftp_mkdirs(ftp, remote_full + "/" + subdir)
                ftp.cwd(remote_full)

            print(f"  Uploading: {remote_file} ({file_path.stat().st_size:,} bytes)")
            with open(file_path, "rb") as f:
                ftp.storbinary(f"STOR {remote_file}", f)
            files_uploaded += 1

    ftp.quit()

    domain_part = args.remote_path.strip("/")
    url = f"https://adspro.projectpro.pl/{domain_part}/"

    print(f"\nUpload zakonczony! {files_uploaded} plikow.")
    print(f"URL: {url}")


if __name__ == "__main__":
    main()
