import argparse
import sys
from pathlib import Path

from .assembler import Assembler


def main():
    parser = argparse.ArgumentParser(description="Hack Assembly Language Assembler")
    parser.add_argument("input_file", help="Path to .asm file to assemble")

    args = parser.parse_args()
    input_path = Path(args.input_file)

    # Validation
    if not input_path.exists():
        print(f"Error: File '{input_path}' does not exist", file=sys.stderr)
        sys.exit(1)

    if input_path.suffix != ".asm":
        print("Error: File must have .asm extension", file=sys.stderr)
        sys.exit(1)

    # Generate output path
    output_path = input_path.with_suffix(".hack")

    # Assemble
    try:
        assembler = Assembler(input_path, output_path)
        assembler.assemble()
    except ValueError as e:
        # Handle validation errors (empty labels, invalid syntax, etc.)
        print(f"Assembly Error: {e}", file=sys.stderr)
        sys.exit(1)
    except FileNotFoundError as e:
        # Handle missing files
        print(f"File Error: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        # Catch any other unexpected errors
        print(f"Unexpected Error: {e}", file=sys.stderr)
        sys.exit(1)
