"""
System Router
Health checks and system information
"""

from fastapi import APIRouter
from app.core.config import settings
from app.core.database import execute_query
from pathlib import Path

# Read version from VERSION file
def get_version():
    try:
        version_file = Path(__file__).parent.parent.parent.parent / "VERSION"
        return version_file.read_text().strip()
    except:
        return "unknown"

router = APIRouter()


@router.get("/system/health")
async def health_check():
    """Comprehensive health check"""
    try:
        # Test database connection
        result = execute_query("SELECT 1 as test")
        db_status = "healthy" if result else "unhealthy"
    except Exception as e:
        db_status = f"unhealthy: {str(e)}"
    
    return {
        "status": "healthy",
        "service": "BMC Hub",
        "version": get_version(),
        "database": db_status,
        "config": {
            "environment": "production" if not settings.ECONOMIC_DRY_RUN else "development",
            "economic_read_only": settings.ECONOMIC_READ_ONLY,
            "economic_dry_run": settings.ECONOMIC_DRY_RUN
        }
    }


@router.get("/system/config")
async def get_config():
    """Get system configuration (non-sensitive)"""
    return {
        "api_host": settings.API_HOST,
        "api_port": settings.API_PORT,
        "log_level": settings.LOG_LEVEL,
        "economic_enabled": bool(settings.ECONOMIC_APP_SECRET_TOKEN),
        "economic_read_only": settings.ECONOMIC_READ_ONLY,
        "economic_dry_run": settings.ECONOMIC_DRY_RUN
    }


@router.get("/system/test-economic")
async def test_economic_connection():
    """Test e-conomic API connection and fetch sample data"""
    try:
        from app.services.economic_service import EconomicService
        economic = EconomicService()
        
        # Test: Fetch first page of customers
        customers = await economic.get_customers(page=0, page_size=5)
        
        return {
            "status": "success",
            "connection": "healthy",
            "api_url": settings.ECONOMIC_API_URL,
            "has_app_secret": bool(settings.ECONOMIC_APP_SECRET_TOKEN),
            "has_agreement_token": bool(settings.ECONOMIC_AGREEMENT_GRANT_TOKEN),
            "read_only_mode": settings.ECONOMIC_READ_ONLY,
            "dry_run_mode": settings.ECONOMIC_DRY_RUN,
            "test_results": {
                "customers_fetched": len(customers) if customers else 0,
                "sample_customers": [
                    {
                        "number": c.get("customerNumber"),
                        "name": c.get("name"),
                        "cvr": c.get("corporateIdentificationNumber")
                    } for c in (customers[:3] if customers else [])
                ]
            }
        }
    except Exception as e:
        return {
            "status": "error",
            "connection": "failed",
            "error": str(e),
            "api_url": settings.ECONOMIC_API_URL,
            "has_app_secret": bool(settings.ECONOMIC_APP_SECRET_TOKEN),
            "has_agreement_token": bool(settings.ECONOMIC_AGREEMENT_GRANT_TOKEN)
        }


@router.get("/system/maintenance")
async def get_maintenance_status():
    """Get maintenance mode status"""
    return {
        "maintenance_mode": False,
        "message": None
    }


@router.get("/system/live-stats")
async def get_live_stats():
    """Get live dashboard statistics"""
    try:
        # Get counts from database
        customers_result = execute_query("SELECT COUNT(*) as count FROM customers")
        tickets_result = execute_query("SELECT COUNT(*) as count FROM tickets WHERE status != 'closed'")
        
        return {
            "sales": {
                "active_orders": 0,
                "pending_quotes": 0
            },
            "customers": {
                "total": customers_result[0]['count'] if customers_result else 0,
                "new_this_month": 0
            },
            "tickets": {
                "open": tickets_result[0]['count'] if tickets_result else 0,
                "in_progress": 0
            }
        }
    except Exception as e:
        return {
            "sales": {"active_orders": 0, "pending_quotes": 0},
            "customers": {"total": 0, "new_this_month": 0},
            "tickets": {"open": 0, "in_progress": 0}
        }


@router.get("/system/recent-activity")
async def get_recent_activity():
    """Get recent system activity"""
    try:
        # Get recent customers
        query = """
            SELECT 
                'customer' as activity_type,
                name,
                created_at,
                'bi-building' as icon,
                'primary' as color
            FROM customers
            ORDER BY created_at DESC
            LIMIT 10
        """
        activities = execute_query(query)
        return activities
    except Exception as e:
        return []
