import os
import sys
import argparse
import socket
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

def get_local_ip():
    """Detect the primary local IP address of the machine."""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # Doesn't need to be reachable, just triggers OS interface selection
        s.connect(('8.8.8.8', 1))
        ip = s.getsockname()[0]
    except Exception:
        ip = '127.0.0.1'
    finally:
        s.close()
    return ip

def main():
    parser = argparse.ArgumentParser(description="LiteFTP Server")
    parser.add_argument("--port", type=int, default=2121, help="Port (default: 2121)")
    parser.add_argument("--dir", type=str, default=os.getcwd(), help="Directory (default: current)")
    args, unknown = parser.parse_known_args()

    print("\n⚡ LITE-FTP SERVER")
    print("="*35)

    try:
        # 1. Configuration (Interactive if not passed via CLI)
        if len(sys.argv) <= 1:
            port_input = input(f"Port [{args.port}]: ").strip()
            port = int(port_input) if port_input else args.port
            
            dir_input = input(f"Directory [{args.dir}]: ").strip()
            serve_dir = dir_input if dir_input else args.dir
        else:
            port = args.port
            serve_dir = args.dir

        if not os.path.isdir(serve_dir):
            print(f"Error: {serve_dir} is not a valid directory.")
            sys.exit(1)

        # 2. Authentication Logic
        print("\n--- Authentication ---")
        user = input("Username: ").strip()
        
        authorizer = DummyAuthorizer()
        
        if not user:
            # ANONYMOUS MODE
            authorizer.add_anonymous(serve_dir, perm='elradfmwMT')
            auth_status = "ANONYMOUS (No password)"
        else:
            # USER MODE
            password = input(f"Password for '{user}': ").strip()
            authorizer.add_user(user, password, serve_dir, perm='elradfmwMT')
            auth_status = f"USER: {user} | PASS: {'<NULL>' if not password else '********'}"

        # 3. Server Initialization
        handler = FTPHandler
        handler.authorizer = authorizer
        handler.banner = "LiteFTP Server Ready."

        address = ('0.0.0.0', port)
        server = FTPServer(address, handler)
        
        # Settings for stability
        server.max_cons = 256
        server.max_cons_per_ip = 10

        print("\n" + "="*35)
        print(f"SERVER ONLINE")
        print(f"Address:  {get_local_ip()}:{port}")
        print(f"Serving:  {serve_dir}")
        print(f"Auth:     {auth_status}")
        print("="*35)
        print("\nPress Ctrl+C to shutdown.\n")

        server.serve_forever()

    except KeyboardInterrupt:
        print("\n\nServer shutting down...")
        sys.exit(0)
    except Exception as e:
        print(f"\nCritical Error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
