import socket
from pathlib import Path
from smb.SMBConnection import SMBConnection

SERVER      = "192.168.45.4"
SHARE       = "AGILENT"
USERNAME    = ""
PASSWORD    = ""
CLIENT_NAME = socket.gethostname()
SERVER_NAME = SERVER

DATA_DIR = Path(__file__).parent / "data"


def _connect():
    conn = SMBConnection(
        USERNAME, PASSWORD,
        CLIENT_NAME, SERVER_NAME,
        use_ntlm_v2=True,
        is_direct_tcp=True
    )
    if not conn.connect(SERVER, 445):
        raise ConnectionError("Failed to connect to SMB share.")
    return conn


def list_csv_files(server=SERVER, share=SHARE, username=USERNAME, password=PASSWORD):
    """Return a list of all .csv paths found on the share (recursive)."""
    conn = _connect()
    csv_files = []

    def walk(path):
        for entry in conn.listPath(share, path):
            if entry.filename in (".", ".."):
                continue
            full_path = f"{path}/{entry.filename}"
            if entry.isDirectory:
                walk(full_path)
            elif entry.filename.lower().endswith(".csv"):
                csv_files.append(full_path)

    try:
        walk("/")
    finally:
        conn.close()

    return csv_files


def transfer_csv_files():
    """
    Copy all .csv files from the scope share to DATA_DIR,
    then delete them from the scope.
    Returns (copied, failed) counts.
    """
    DATA_DIR.mkdir(exist_ok=True)
    conn = _connect()
    copied = 0
    failed = 0

    try:
        csv_files = []

        def walk(path):
            for entry in conn.listPath(SHARE, path):
                if entry.filename in (".", ".."):
                    continue
                full_path = f"{path}/{entry.filename}"
                if entry.isDirectory:
                    walk(full_path)
                elif entry.filename.lower().endswith(".csv"):
                    csv_files.append(full_path)

        walk("/")

        for remote_path in csv_files:
            filename = Path(remote_path).name
            local_path = DATA_DIR / filename
            try:
                with open(local_path, "wb") as f:
                    conn.retrieveFile(SHARE, remote_path, f)
                conn.deleteFiles(SHARE, remote_path)
                print(f"  TRANSFERRED: {filename}")
                copied += 1
            except Exception as e:
                print(f"  FAILED: {filename} — {e}")
                failed += 1

    finally:
        conn.close()

    return copied, failed


if __name__ == "__main__":
    print(f"Transferring CSV files from \\\\{SERVER}\\{SHARE} to {DATA_DIR}...\n")
    copied, failed = transfer_csv_files()
    print(f"\nDone. {copied} transferred, {failed} failed.")
