"""Device Doctor - Main Entry Point."""

import sys
import logging
from pathlib import Path

# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))

from doctor.diagnostics.analyzer import analyze_system
from doctor.ai.explainer import AIExplainer
from doctor.report.formatter import format_report


# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger(__name__)


def main():
    """Main entry point for Device Doctor."""
    logger.info("Device Doctor Phase-1 Starting...")
    logger.info("Mode: Read-Only Diagnostic Agent")
    logger.info("")
    
    try:
        # Step 1: Analyze system
        logger.info("Step 1: Analyzing system...")
        diagnostic_result = analyze_system()
        
        # Step 2: Generate AI explanations
        logger.info("Step 2: Generating explanations...")
        explainer = AIExplainer(use_ai=True)
        report = explainer.explain(
            diagnostic_result.symptoms,
            diagnostic_result.matching_rules,
            diagnostic_result.telemetry
        )
        
        # Step 3: Format and display report
        logger.info("Step 3: Formatting report...")
        formatted_report = format_report(
            report,
            diagnostic_result.symptoms,
            diagnostic_result.telemetry
        )
        
        print("\n")
        print(formatted_report)
        print("\n")
        
        logger.info("Device Doctor analysis complete.")
        
        return 0
        
    except KeyboardInterrupt:
        logger.info("Analysis interrupted by user.")
        return 130
    except Exception as e:
        logger.error(f"Fatal error during analysis: {e}", exc_info=True)
        print("\nError: Device Doctor encountered a fatal error.")
        print(f"Details: {str(e)}")
        return 1


if __name__ == "__main__":
    sys.exit(main())
