from m365_user_manager.managers.environment_manager import EnvironmentManager
from typing import Any
import json
from pathlib import Path

class ResultHandler:
    """
    Manages operation results and output formatting.
    
    Handles result processing, logging, and output generation for both
    local and Asio environments.
    
    Usage:
        handler = ResultHandler()
        # For Asio environment
        handler.handle_asio_result(result_dict)
        # For local environment
        handler.handle_local_result(result_dict)
        
    Methods:
        handle_asio_result(): Processes results for Asio environment
        handle_local_result(): Processes results for local environment
    """
    def __init__(self, discord_webhook_url: str = None):
        self.discord_webhook_url = discord_webhook_url
        self.logger = EnvironmentManager(discord_webhook_url=self.discord_webhook_url).setup_logging()

    def handle_asio_result(self, result: dict[str, Any]) -> None:
        """Handle results in Asio environment."""
        if not result:
            self.logger.error("User creation failed")
            self.logger.result_failed_message("User creation failed")
            return

        result_data = {
            "user_id": result["user_id"],
            "status": "success",
            "message": "User created successfully",
            "email": result["email"],
            "password_link": result["password_link"],
            "assigned": result["licenses"]["assigned"],
            "unavailable": result["licenses"]["unavailable"],
            "available_str": result["licenses"]["available_str"],
            "unavailable_str": result["licenses"]["unavailable_str"],
            "groups": result["groups"]
        }

        self.logger.info(f"Result data: {json.dumps(result_data, indent=2)}")
        self.logger.result_data(result_data)

    def handle_local_result(self, result: dict[str, Any]) -> None:
        """Handle results in local environment."""
        if not result:
            self.logger.info("\nUser creation failed!")
            return

        self.logger.info("\nUser created successfully!")
        self.logger.info(f"Email: {result['email']}")
        self.logger.info(f"Initial password: {result['password']}")
        self.logger.info(f"Password link: {result['password_link']}")
        
        if result['licenses']['available_str']:
            self.logger.info("\nAssigned licenses:")
            self.logger.info(result['licenses']['available_str'])
        if result['licenses']['unavailable_str']:
            self.logger.info("\nUnavailable licenses:")
            self.logger.info(result['licenses']['unavailable_str'])
        
        if result['groups']['successful']:
            self.logger.info("\nAdded to groups:")
            self.logger.info("\n".join(result['groups']['successful']))
        if result['groups']['failed']:
            self.logger.info("\nFailed to add to groups:")
            self.logger.info("\n".join(result['groups']['failed']))

        result_path = Path(__file__).parent / "results"
        result_path.mkdir(parents=True, exist_ok=True)
        result_file = result_path / "user_creation_result.json"
        
        self.logger.info(f"Writing result to {result_file}")
        self.logger.info(f"Result data: {json.dumps(result, indent=2)}")

        with open(result_file, 'w') as f:
            json.dump(result, f, indent=2)