"""
undisable-adafruit-io-feeds.py

Evaluates all Adafruit IO feeds, identifies disabled feeds, by group if any, and
automatically deletes and recreates each disabled feed. It offers an interactive
mode for step-by-step confirmation and an automated mode for direct processing.
"""
# Change these or set environment variables / pass arguments
DEFAULT_ADAFRUIT_IO_USERNAME = 'YOUR_ADAFRUIT_IO_USERNAME'
DEFAULT_ADAFRUIT_IO_KEY = 'YOUR_ADAFRUIT_IO_KEY'
DEBUG = False


import sys
import os
import argparse
import time
from Adafruit_IO import Client, RequestError, Feed

# Command-line Argument Parser Setup
parser = argparse.ArgumentParser(description="Manage Adafruit IO feeds.")
parser.add_argument("-a", "--automated", help="Enable automated mode", action="store_true")
parser.add_argument("-u", "--username", help="Adafruit IO Username", type=str)
parser.add_argument("-k", "--key", help="Adafruit IO Key", type=str)
args = parser.parse_args()

# Environment Variables / Arguments / Defaults
ADAFRUIT_IO_USERNAME = args.username or os.environ.get("ADAFRUIT_IO_USERNAME", DEFAULT_ADAFRUIT_IO_USERNAME)
ADAFRUIT_IO_KEY = args.key or os.environ.get("ADAFRUIT_IO_KEY", DEFAULT_ADAFRUIT_IO_KEY)

def main():
    """
    Main function to handle the feed management process.
    """
    # Initialize Adafruit IO Client
    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    # Determine mode
    mode = 'automated' if args.automated else 'interactive'
    if mode == 'interactive':
        print("Running in interactive mode. Use -a or --automated for automated mode.")

    try:
        print("Fetching groups and their feeds...")
        # Fetch all groups and their feeds
        groups = aio.groups()
        for group in groups:
            if group.description == 'A WipperSnapper Device':
                print("** Found WipperSnapper group:", group.name)
                print("Export WipperSnapper device config and re-import instead of deleting and recreating feeds!!!")
                print(f"https://io.adafruit.com/{ADAFRUIT_IO_USERNAME}/devices/{group.key}")
                continue
            for feed in group.feeds:
                if hasattr(feed, "enabled") and feed.enabled is False:
                    print(f"Found disabled feed in group '{group.name}': {feed.name}")

                    if mode == 'interactive':
                        confirm = input(f"Do you want to delete and recreate the feed '{feed.name}' in group '{group.name}'? (y/N): ").strip().upper()
                        if confirm != 'Y':
                            continue

                    if DEBUG:
                        print("DEBUG: Old feed")
                        print("DEBUG: obj:", feed)
                        print("")

                    # Delete the disabled feed
                    print(f"Deleting feed: {feed.name}")
                    aio.delete_feed(feed.key)
                    # Wait for Adafruit IO to process the deletion
                    time.sleep(0.25)

                    print("Enabling feed in cloned object...")
                    feed = feed._replace(enabled=True)
                    
                    if DEBUG:
                        print("DEBUG: Enabled feed clone - double check!!!")
                        print("DEBUG: obj:", feed)
                        print("")

                    # Recreate the feed with the same settings
                    print(f"Recreating feed: {feed.name}")
                    new_feed = aio.create_feed(feed, group.key if group.key else None) # Reassign to group
                    print(f"Successfully recreated and reassigned feed: {new_feed.name} to group '{group.name}'")

                    if DEBUG:
                        print("DEBUG: New feed")
                        print("DEBUG: obj:", new_feed)
                        print("")

                else:
                    print(f"Skipping enabled feed: {feed.name}")

    except RequestError as e:
        print(f"An error occurred: {e}")
        sys.exit(1)

    print("Feed management completed.")

if __name__ == "__main__":
    main()