#!/usr/bin/env python3
"""Build PeerDrop executables using PyInstaller.

Usage:
    python build/build.py              # Build both CLI and GUI
    python build/build.py --cli        # Build CLI only
    python build/build.py --gui        # Build GUI only
    python build/build.py --clean      # Clean build artifacts first
"""

import argparse
import os
import platform
import shutil
import subprocess
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BUILD_DIR = os.path.dirname(os.path.abspath(__file__))
DIST_DIR = os.path.join(ROOT, 'dist')


def clean():
    """Remove previous build artifacts."""
    for d in ['build', 'dist']:
        path = os.path.join(ROOT, d)
        if not os.path.exists(path):
            continue
        if d == 'build':
            # Only clean build contents, not the script itself
            for item in os.listdir(path):
                item_path = os.path.join(path, item)
                if item.endswith(('.py', '.spec')):
                    continue  # Keep our scripts
                if os.path.isfile(item_path):
                    os.remove(item_path)
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
        else:
            print(f"Cleaning {path}")
            shutil.rmtree(path)


def build_cli():
    """Build the CLI executable."""
    spec = os.path.join(BUILD_DIR, 'peerdrop_cli.spec')
    print(f"\n{'='*60}")
    print("Building CLI (peerdrop)...")
    print(f"{'='*60}")
    cmd = [sys.executable, '-m', 'PyInstaller', '--noconfirm', spec]
    result = subprocess.run(cmd, cwd=ROOT)
    if result.returncode != 0:
        print("CLI build failed!")
        return False
    print("CLI build successful!")
    return True


def build_gui():
    """Build the GUI executable."""
    spec = os.path.join(BUILD_DIR, 'peerdrop_gui.spec')
    print(f"\n{'='*60}")
    print("Building GUI (peerdrop-gui)...")
    print(f"{'='*60}")
    cmd = [sys.executable, '-m', 'PyInstaller', '--noconfirm', spec]
    result = subprocess.run(cmd, cwd=ROOT)
    if result.returncode != 0:
        print("GUI build failed!")
        return False
    print("GUI build successful!")
    return True


def print_result():
    """Print build results."""
    system = platform.system()
    print(f"\n{'='*60}")
    print(f"Build complete! ({system})")
    print(f"{'='*60}")

    if os.path.exists(DIST_DIR):
        print(f"\nOutput directory: {DIST_DIR}")
        for item in sorted(os.listdir(DIST_DIR)):
            path = os.path.join(DIST_DIR, item)
            if os.path.isfile(path):
                size_mb = os.path.getsize(path) / (1024 * 1024)
                print(f"  {item:30} {size_mb:.1f} MB")
            elif os.path.isdir(path):
                total = 0
                for dirpath, _, filenames in os.walk(path):
                    for f in filenames:
                        fp = os.path.join(dirpath, f)
                        total += os.path.getsize(fp)
                size_mb = total / (1024 * 1024)
                print(f"  {item:30} {size_mb:.1f} MB (directory)")

        print()
        if system == 'Darwin':
            print("To run the GUI:  dist/peerdrop-gui/peerdrop-gui")
            print("To run the app:  open dist/PeerDrop.app")
            print("To run the CLI:  dist/peerdrop")
        elif system == 'Windows':
            print("To run the GUI:  dist\\peerdrop-gui\\peerdrop-gui.exe")
            print("To run the CLI:  dist\\peerdrop.exe")
        else:
            print("To run the GUI:  ./dist/peerdrop-gui/peerdrop-gui")
            print("To run the CLI:  ./dist/peerdrop")


def main():
    parser = argparse.ArgumentParser(description='Build PeerDrop executables')
    parser.add_argument('--cli', action='store_true', help='Build CLI only')
    parser.add_argument('--gui', action='store_true', help='Build GUI only')
    parser.add_argument('--clean', action='store_true', help='Clean before building')
    args = parser.parse_args()

    build_both = not args.cli and not args.gui

    if args.clean:
        clean()

    success = True

    if build_both or args.cli:
        if not build_cli():
            success = False

    if build_both or args.gui:
        if not build_gui():
            success = False

    if success:
        print_result()
    else:
        print("\nBuild completed with errors.")
        sys.exit(1)


if __name__ == '__main__':
    main()
