"""
Main entry point for piRTC package
Provides unified CLI for all piRTC functions
"""

import os
import sys
import argparse
import logging

def setup_logging(verbose=False):
    """Setup logging configuration"""
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(
        description='piRTC - Raspberry Pi RTC & WatchDog Management',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  piRTC shell              # Start interactive CLI shell
  piRTC server             # Start web API server
  piRTC status             # Show system status
  piRTC rtc-time           # Read RTC time
  piRTC rtc-set 14 30 0    # Set RTC time
  piRTC wd-feed            # Feed watchdog
        """
    )
    
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        help='Enable verbose logging'
    )
    
    parser.add_argument(
        '--mock',
        action='store_true',
        help='Enable mock mode (no hardware required)'
    )
    
    parser.add_argument(
        '--config', '-c',
        default='.env',
        help='Configuration file (default: .env)'
    )
    
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Shell command
    shell_parser = subparsers.add_parser(
        'shell',
        help='Start interactive CLI shell'
    )
    
    # Server command
    server_parser = subparsers.add_parser(
        'server',
        help='Start web API server'
    )
    server_parser.add_argument(
        '--host',
        default='0.0.0.0',
        help='Server host (default: 0.0.0.0)'
    )
    server_parser.add_argument(
        '--port', '-p',
        type=int,
        default=8080,
        help='Server port (default: 8080)'
    )
    
    # Status command
    status_parser = subparsers.add_parser(
        'status',
        help='Show system status'
    )
    
    # RTC commands
    rtc_parser = subparsers.add_parser(
        'rtc',
        help='RTC commands'
    )
    rtc_subparsers = rtc_parser.add_subparsers(dest='rtc_command')
    
    rtc_time_parser = rtc_subparsers.add_parser('time', help='Read RTC time')
    rtc_date_parser = rtc_subparsers.add_parser('date', help='Read RTC date')
    rtc_temp_parser = rtc_subparsers.add_parser('temp', help='Read RTC temperature')
    rtc_info_parser = rtc_subparsers.add_parser('info', help='Show RTC info')
    
    rtc_set_time_parser = rtc_subparsers.add_parser('set-time', help='Set RTC time')
    rtc_set_time_parser.add_argument('hour', type=int, help='Hour (0-23)')
    rtc_set_time_parser.add_argument('minute', type=int, help='Minute (0-59)')
    rtc_set_time_parser.add_argument('second', type=int, help='Second (0-59)')
    
    rtc_set_date_parser = rtc_subparsers.add_parser('set-date', help='Set RTC date')
    rtc_set_date_parser.add_argument('year', type=int, help='Year (2000-2099)')
    rtc_set_date_parser.add_argument('month', type=int, help='Month (1-12)')
    rtc_set_date_parser.add_argument('day', type=int, help='Day (1-31)')
    
    rtc_sync_sys_parser = rtc_subparsers.add_parser('sync-to-system', help='Sync RTC to system')
    rtc_sync_rtc_parser = rtc_subparsers.add_parser('sync-from-system', help='Sync system to RTC')
    
    # WatchDog commands
    wd_parser = subparsers.add_parser(
        'watchdog',
        aliases=['wd'],
        help='WatchDog commands'
    )
    wd_subparsers = wd_parser.add_subparsers(dest='wd_command')
    
    wd_feed_parser = wd_subparsers.add_parser('feed', help='Feed watchdog')
    wd_info_parser = wd_subparsers.add_parser('info', help='Show watchdog info')
    wd_version_parser = wd_subparsers.add_parser('version', help='Get watchdog version')
    wd_test_parser = wd_subparsers.add_parser('test', help='Run watchdog test loop')
    
    # I2C scan command
    i2c_parser = subparsers.add_parser(
        'i2c-scan',
        help='Scan I2C bus'
    )
    
    # Parse arguments
    args = parser.parse_args()
    
    # Setup logging
    setup_logging(args.verbose)
    
    # Load environment if config file exists
    if os.path.exists(args.config):
        from dotenv import load_dotenv
        load_dotenv(args.config)
    
    # Set mock mode
    if args.mock:
        os.environ['RTC_MOCK'] = 'true'
    
    # Execute command
    if args.command == 'shell':
        from .shell import RTCShell
        shell = RTCShell()
        shell.run()
    
    elif args.command == 'server':
        import uvicorn
        from .api import app
        uvicorn.run(app, host=args.host, port=args.port)
    
    elif args.command == 'status':
        from .rtc import RTCManager
        from .watchdog import WatchDogManager
        
        rtc_addr = int(os.environ.get('RTC_I2C_ADDRESS', '0x68'), 16)
        wd_addr = int(os.environ.get('WATCHDOG_I2C_ADDRESS', '0x67'), 16)
        wd_gpio = int(os.environ.get('WATCHDOG_GPIO_PIN', '4'))
        mock = os.environ.get('RTC_MOCK', 'false').lower() == 'true'
        
        rtc = RTCManager(i2c_address=rtc_addr, mock=mock)
        wd = WatchDogManager(i2c_address=wd_addr, gpio_pin=wd_gpio, mock=mock)
        
        print("\n" + "="*40)
        print("piRTC System Status")
        print("="*40)
        
        rtc_status = rtc.get_status()
        print(f"\nRTC:")
        for key, value in rtc_status.items():
            print(f"  {key}: {value}")
        
        wd_status = wd.get_status()
        print(f"\nWatchDog:")
        for key, value in wd_status.items():
            print(f"  {key}: {value}")
        
        print("\n" + "="*40 + "\n")
    
    elif args.command == 'rtc':
        from .rtc import RTCManager
        
        rtc_addr = int(os.environ.get('RTC_I2C_ADDRESS', '0x68'), 16)
        mock = os.environ.get('RTC_MOCK', 'false').lower() == 'true'
        rtc = RTCManager(i2c_address=rtc_addr, mock=mock)
        
        if args.rtc_command == 'time':
            time_data = rtc.read_time()
            if time_data:
                print(f"{time_data['hour']:02d}:{time_data['minute']:02d}:{time_data['second']:02d}")
        
        elif args.rtc_command == 'date':
            date_data = rtc.read_date()
            if date_data:
                print(f"{date_data['year']}-{date_data['month']:02d}-{date_data['day']:02d}")
        
        elif args.rtc_command == 'temp':
            temp_data = rtc.read_temperature()
            if temp_data:
                print(f"{temp_data['temperature']:.2f}")
        
        elif args.rtc_command == 'info':
            import json
            print(json.dumps(rtc.get_status(), indent=2))
        
        elif args.rtc_command == 'set-time':
            if rtc.set_time(args.hour, args.minute, args.second):
                print("Time set successfully")
            else:
                print("Failed to set time")
                sys.exit(1)
        
        elif args.rtc_command == 'set-date':
            if rtc.set_date(args.year, args.month, args.day):
                print("Date set successfully")
            else:
                print("Failed to set date")
                sys.exit(1)
        
        elif args.rtc_command == 'sync-to-system':
            if rtc.sync_to_system():
                print("System time synchronized")
            else:
                print("Failed to sync")
                sys.exit(1)
        
        elif args.rtc_command == 'sync-from-system':
            if rtc.sync_from_system():
                print("RTC synchronized with system time")
            else:
                print("Failed to sync")
                sys.exit(1)
    
    elif args.command in ['watchdog', 'wd']:
        from .watchdog import WatchDogManager
        
        wd_addr = int(os.environ.get('WATCHDOG_I2C_ADDRESS', '0x67'), 16)
        wd_gpio = int(os.environ.get('WATCHDOG_GPIO_PIN', '4'))
        mock = os.environ.get('RTC_MOCK', 'false').lower() == 'true'
        wd = WatchDogManager(i2c_address=wd_addr, gpio_pin=wd_gpio, mock=mock)
        
        if args.wd_command == 'feed':
            if wd.feed():
                print("WatchDog fed")
            else:
                print("Failed to feed WatchDog")
                sys.exit(1)
        
        elif args.wd_command == 'info':
            import json
            print(json.dumps(wd.get_status(), indent=2))
        
        elif args.wd_command == 'version':
            version = wd.get_version()
            if version:
                print(version['version'])
            else:
                print("Unknown")
                sys.exit(1)
        
        elif args.wd_command == 'test':
            wd.test_feed_loop(count=10, interval=2.0)
    
    elif args.command == 'i2c-scan':
        import subprocess
        try:
            result = subprocess.run(['i2cdetect', '-y', '1'], capture_output=True, text=True)
            print(result.stdout)
        except Exception as e:
            print(f"Error: {e}")
            sys.exit(1)
    
    else:
        parser.print_help()

if __name__ == "__main__":
    main()
