import subprocess

from common_logging import get_logger

from ..base import JobStatus, TrainingConfig, TrainingPlatform, TrainingResult

logger = get_logger(__name__)


class AutoPlatform(TrainingPlatform):

    def __init__(self):
        self._delegate = self._detect_platform()

    def _detect_platform(self) -> TrainingPlatform:
        try:
            result = subprocess.run(['uname', '-m'], capture_output=True, text=True, timeout=5)
            if result.stdout.strip() == 'arm64':
                system = subprocess.run(['uname', '-s'], capture_output=True, text=True, timeout=5)
                if system.stdout.strip() == 'Darwin':
                    try:
                        from .mlx import MLXPlatform
                        return MLXPlatform()
                    except ImportError:
                        logger.debug("MLX not available")
        except Exception as e:
            logger.debug("Platform detection skipped", error=str(e))
        try:
            result = subprocess.run(['nvidia-smi'], capture_output=True, timeout=5)
            if result.returncode == 0:
                from .llamafactory import LlamaFactoryPlatform
                return LlamaFactoryPlatform()
        except Exception as e:
            logger.debug("NVIDIA GPU not detected", error=str(e))
        raise RuntimeError('No available training environment detected (Apple Silicon or NVIDIA GPU)')

    def create_training_job(self, config: TrainingConfig) -> str:
        return self._delegate.create_training_job(config)

    def get_job_status(self, job_id: str) -> JobStatus:
        return self._delegate.get_job_status(job_id)

    def get_job_result(self, job_id: str) -> TrainingResult:
        return self._delegate.get_job_result(job_id)

    def cancel_job(self, job_id: str) -> bool:
        return self._delegate.cancel_job(job_id)
