#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Диагностический скрипт для определения совместимых API
"""

import os
import sys
import logging
import argparse
from pathlib import Path

# Добавляем родительскую директорию в sys.path
parent_dir = str(Path(__file__).resolve().parent.parent)
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

from src.api.api_discovery import discover_available_apis
from src.config.config import SYNOLOGY_HOST, SYNOLOGY_PORT, SYNOLOGY_SECURE

# Настройка логгера
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def main():
    """Точка входа для диагностического скрипта"""
    parser = argparse.ArgumentParser(description='Synology API Diagnostic Tool')
    parser.add_argument('--host', help='Synology host address', default=SYNOLOGY_HOST)
    parser.add_argument('--port', type=int, help='Synology host port', default=SYNOLOGY_PORT)
    parser.add_argument('--secure', action='store_true', help='Use HTTPS', default=SYNOLOGY_SECURE)
    
    args = parser.parse_args()
    
    protocol = "https" if args.secure else "http"
    base_url = f"{protocol}://{args.host}:{args.port}/webapi"
    
    print(f"Scanning APIs at {base_url}...")
    
    apis = discover_available_apis(base_url)
    
    if not apis:
        print("No APIs were discovered. Check connection parameters.")
        return
        
    print(f"Discovered {len(apis)} APIs")
    
    # Анализ результатов
    
    # 1. Ищем API для управления питанием
    print("\nPower Management APIs:")
    power_apis = [name for name in apis.keys() if "power" in name.lower()]
    for api in power_apis:
        info = apis[api]
        print(f"  - {api} (v{info.get('minVersion', 1)}-{info.get('maxVersion', 1)}), path: {info.get('path', 'entry.cgi')}")
    
    # 2. Ищем API для информации о системе
    print("\nSystem Information APIs:")
    system_info_apis = [name for name in apis.keys() if ("system" in name.lower() or "dsm" in name.lower()) and "info" in name.lower()]
    for api in system_info_apis:
        info = apis[api]
        print(f"  - {api} (v{info.get('minVersion', 1)}-{info.get('maxVersion', 1)}), path: {info.get('path', 'entry.cgi')}")
    
    # 3. Ищем API для перезагрузки
    print("\nReboot/Restart APIs:")
    reboot_apis = [name for name in apis.keys() if any(word in name.lower() for word in ["restart", "reboot", "power"])]
    for api in reboot_apis:
        info = apis[api]
        print(f"  - {api} (v{info.get('minVersion', 1)}-{info.get('maxVersion', 1)}), path: {info.get('path', 'entry.cgi')}")
    
    print("\nRecommended API Settings:")
    
    if power_apis:
        recommended_power_api = max(power_apis, key=lambda x: apis[x].get('maxVersion', 1))
        print(f"Power API: {recommended_power_api}, version: {apis[recommended_power_api].get('maxVersion', 1)}")
    else:
        print("Power API: Not found, falling back to SYNO.Core.System")
        
    if system_info_apis:
        recommended_info_api = max(system_info_apis, key=lambda x: apis[x].get('maxVersion', 1))
        print(f"System Info API: {recommended_info_api}, version: {apis[recommended_info_api].get('maxVersion', 1)}")
    else:
        print("System Info API: Not found, falling back to SYNO.DSM.Info")
        
    print("\nThese settings should be added to your .env file.")

if __name__ == "__main__":
    main()
