#!/usr/bin/env python3

import os
import sys
import argparse
from pathlib import Path

def remove_as_entry(as_id, dry_run=False):
    """Remove an AS entry from the WHOIS database"""
    # Get the database path
    script_dir = Path(__file__).parent
    db_dir = script_dir / 'db' / 'as'
    
    # Construct the file path
    as_file = db_dir / as_id
    
    # Check if the file exists
    if not as_file.exists():
        print(f"Error: AS entry '{as_id}' not found in database")
        return False
    
    # Read and display the entry before deletion
    print(f"\nAS entry to be removed:")
    print("-" * 50)
    with open(as_file, 'r') as f:
        print(f.read())
    print("-" * 50)
    
    if dry_run:
        print("\n[DRY RUN] Would remove:", as_file)
        return True
    
    # Confirm deletion
    response = input(f"\nAre you sure you want to remove AS {as_id}? (yes/no): ")
    if response.lower() != 'yes':
        print("Deletion cancelled")
        return False
    
    # Remove the file
    try:
        os.remove(as_file)
        print(f"\nSuccessfully removed AS entry: {as_id}")
        return True
    except Exception as e:
        print(f"Error removing AS entry: {e}")
        return False

def main():
    parser = argparse.ArgumentParser(
        description='Remove an AS entry from the WHOIS database',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  ./remove-as 60284                    # Remove AS 60284
  ./remove-as 76-60284                 # Remove AS 76-60284
  ./remove-as 2:0:17                   # Remove AS 2:0:17
  ./remove-as --dry-run 60284          # Show what would be removed without deleting
        """
    )
    
    parser.add_argument('as_id', help='AS identifier to remove (e.g., 60284, 76-60284, 2:0:17)')
    parser.add_argument('--dry-run', action='store_true', 
                        help='Show what would be removed without actually deleting')
    
    args = parser.parse_args()
    
    # Remove the AS entry
    success = remove_as_entry(args.as_id, args.dry_run)
    
    # Exit with appropriate code
    sys.exit(0 if success else 1)

if __name__ == '__main__':
    main()