"""Configuration management for FWAuto."""

import platform
import sys
import tomllib
from pathlib import Path
from typing import Any

import tomli_w

from .scenario import Scenario, ScenarioManager


def detect_platform() -> str:
    """Detect the current platform."""
    system = platform.system().lower()

    # Check for WSL (Windows Subsystem for Linux)
    if system == "linux" and "microsoft" in platform.release().lower():
        # WSL is treated as Linux for our purposes
        return "linux"

    return system


def print_config_info():
    """Print current configuration information for debugging."""
    platform_info = detect_platform()

    print("🔧 FWAuto Configuration:")
    print(f"  Platform: {platform_info}")
    print(f"  Python: {sys.version}")
    print(f"  OS Info: {platform.platform()}")


class ConfigError(Exception):
    """Configuration related errors."""

    pass


class ProjectConfig:
    """Project configuration from .fwauto/config.toml."""

    _tmp_remote_log_path: str = ""

    def __init__(self, config_path: Path):
        self.config_path = config_path
        self.data = self._load()
        self._validate()

    def _load(self) -> dict[str, Any]:
        """Load TOML configuration."""
        try:
            with open(self.config_path, "rb") as f:
                return tomllib.load(f)
        except FileNotFoundError:
            raise ConfigError(f"Config file not found: {self.config_path}")
        except Exception as e:
            raise ConfigError(f"Failed to load config: {e}")

    def _validate(self) -> None:
        """Validate configuration schema."""
        # Config 所有欄位都是可選的，使用預設值
        pass

    @property
    def project_name(self) -> str:
        """專案名稱，預設為目錄名"""
        return self.data.get("project", {}).get("name", self.config_path.parent.parent.name)

    @property
    def project_language(self) -> str:
        """專案語言設定，預設為 en"""
        return self.data.get("project", {}).get("language", "en")

    @property
    def build_script(self) -> str:
        """Build script 路徑，預設為 .fwauto/scripts/build_makefile.py"""
        return self.data.get("build", {}).get("script", ".fwauto/scripts/build_makefile.py")

    @property
    def deploy_script(self) -> str:
        """Deploy script 路徑，預設為 .fwauto/scripts/deploy_network.py"""
        return self.data.get("deploy", {}).get("script", ".fwauto/scripts/deploy_network.py")

    @property
    def build_makefile(self) -> str:
        """Build Makefile 路徑，預設為 .fwauto/build/Makefile"""
        return self.data.get("build", {}).get("makefile", ".fwauto/build/Makefile")

    @property
    def build_target(self) -> str:
        """Build target 名稱，預設為 build"""
        return self.data.get("build", {}).get("target", "build")

    @property
    def build_type(self) -> str:
        """Build type: makefile, command"""
        return self.data.get("build", {}).get("type", "makefile")

    @property
    def deploy_type(self) -> str:
        """Deploy type: network, serial, command"""
        return self.data.get("deploy", {}).get("type", "network")

    @property
    def log_type(self) -> str:
        """Log type: file, network, serial (auto-inferred from deploy_type if not set)"""
        log_section = self.data.get("log", {})
        if "type" in log_section:
            return log_section["type"]
        # 向後兼容：從 deploy_type 推斷
        deploy_type = self.deploy_type
        if deploy_type == "serial":
            return "serial"
        return "network"  # 預設

    @property
    def log_path(self) -> str | None:
        """本地日誌路徑 (file 類型用)"""
        return self.data.get("log", {}).get("path")

    @property
    def log_remote_path(self) -> str | None:
        """遠端日誌路徑 (network 類型用)，格式: user@host:path"""
        return self.data.get("log", {}).get("remote_path")

    @property
    def log_serial_port(self) -> str | None:
        """串口裝置 (serial 類型用)"""
        return self.data.get("log", {}).get("serial_port")

    @property
    def log_baudrate(self) -> int:
        """串口波特率，預設 115200"""
        return self.data.get("log", {}).get("baudrate", 115200)

    def is_log_configured(self) -> bool:
        """檢查 log 是否已配置"""
        log_section = self.data.get("log", {})
        log_type = self.log_type

        if log_type == "file":
            return bool(log_section.get("path"))
        elif log_type == "network":
            # 檢查 remote_path 或 last_log_file_path
            return bool(log_section.get("remote_path") or log_section.get("last_log_file_path"))
        elif log_type == "serial":
            return bool(log_section.get("serial_port"))
        return False

    @property
    def sdk_path(self) -> str | None:
        """SDK 路徑從 Project Config 讀取"""
        return self.data.get("sdk", {}).get("path")

    @property
    def device_family(self) -> str:
        """取得裝置系列 (e.g., stm32f4)"""
        return self.data.get("device", {}).get("family", "")

    @property
    def device_model(self) -> str:
        """取得裝置型號 (e.g., STM32F407VGT6)"""
        return self.data.get("device", {}).get("model", "")

    @property
    def ai_model(self) -> str | None:
        """AI model name from [project] section, None if not set"""
        return self.data.get("project", {}).get("model")

    @property
    def ai_log_level(self) -> str:
        """AI API log level from [project] section, defaults to OFF"""
        return self.data.get("project", {}).get("ai_log_level", "OFF")

    @property
    def deployment_config(self) -> dict[str, Any]:
        """
        Deployment 配置從 Project Config 的 [deployment] 區塊讀取

        Returns:
            包含 board_ip, board_user, deploy_path, ssh_options 的字典
        """
        deployment_section = self.data.get("deployment", {})

        # 只取非 dict 的值（排除可能的子區塊）
        return {k: v for k, v in deployment_section.items() if not isinstance(v, dict)}

    @property
    def board_ip(self) -> str:
        """開發板 IP 地址"""
        ip = self.deployment_config.get("board_ip")
        if not ip:
            raise ConfigError(
                f"board_ip not configured.\n"
                f"\n"
                f"Please configure in: {self.config_path}\n"
                f"  [deployment]\n"
                f'  board_ip = "192.168.x.x"\n'
            )
        return ip

    @property
    def board_user(self) -> str:
        """SSH 登入使用者"""
        return self.deployment_config.get("board_user", "root")

    @property
    def deploy_path(self) -> str:
        """遠端部署目錄"""
        return self.deployment_config.get("deploy_path", "/home/root")

    @property
    def ssh_options(self) -> str:
        """SSH 選項"""
        default_opts = "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=5"
        return self.deployment_config.get("ssh_options", default_opts)

    @property
    def remote_log_enabled(self) -> bool:
        """是否啟用遠端日誌檔案"""
        return self.deployment_config.get("remote_log_enabled", True)

    @property
    def remote_log_pattern(self) -> str:
        """遠端日誌檔案命名模板 (Jinja2 格式)"""
        default_pattern = "{{ deploy_path }}/{{ app_name }}_{{ date }}.log"
        return self.deployment_config.get("remote_log_pattern", default_pattern)

    @property
    def last_log_file_path(self) -> str | None:
        """上次產生的日誌路徑（程式自動寫入，統一存放在 [log] section）"""
        return self.data.get("log", {}).get("last_log_file_path")

    def update_last_log_path(self, log_path: str) -> None:
        """
        更新 last_log_file_path 到 config.toml 的 [log] section

        Args:
            log_path: 日誌路徑（本地或遠端格式皆可）
        """
        from .logging_config import get_logger

        logger = get_logger(__name__)

        # 讀取現有 config
        if self.config_path.exists():
            with open(self.config_path, "rb") as f:
                config_data = tomllib.load(f)
        else:
            config_data = {}

        # 確保 log 區塊存在
        if "log" not in config_data:
            config_data["log"] = {}

        # 寫入 log.last_log_file_path
        config_data["log"]["last_log_file_path"] = log_path

        # 寫回檔案
        with open(self.config_path, "wb") as f:
            tomli_w.dump(config_data, f)

        logger.debug(f"💾 Updated last_log_file_path in config: {log_path}")

    def get_scenarios(self) -> list[Scenario]:
        """
        載入 Project Config 中的所有 scenarios.

        Returns:
            List of Scenario objects from config
        """
        scenarios_data = self.data.get("scenarios", [])
        return [Scenario.from_dict(s) for s in scenarios_data]

    def get_scenario_manager(self) -> ScenarioManager:
        """
        建立 ScenarioManager.

        Returns:
            ScenarioManager instance with project scenarios
        """
        project_scenarios = self.get_scenarios()
        return ScenarioManager(project_scenarios)


def find_project_root(start_path: Path | None = None) -> Path | None:
    """
    向上搜尋 .fwauto/ 目錄,找到專案根目錄.

    Args:
        start_path: 搜尋起點,預設為當前目錄

    Returns:
        專案根目錄 Path,若未找到則返回 None
    """
    if start_path is None:
        start_path = Path.cwd()

    current = start_path.resolve()

    # 向上搜尋,最多到根目錄
    while True:
        fwauto_dir = current / ".fwauto"
        if fwauto_dir.is_dir():
            return current

        # 到達根目錄
        if current.parent == current:
            return None

        current = current.parent


def load_project_config(project_root: Path) -> ProjectConfig:
    """Load project configuration."""
    config_path = project_root / ".fwauto" / "config.toml"
    return ProjectConfig(config_path)


def create_default_config(project_root: Path) -> None:
    """Create default .fwauto/config.toml.

    空白配置，所有設定使用預設值。
    build 和 flash 路徑由 ProjectConfig 屬性提供。
    """
    config_dir = project_root / ".fwauto"
    config_dir.mkdir(exist_ok=True)

    # 空白配置 - 所有設定使用預設值
    config_data = {}

    config_path = config_dir / "config.toml"
    with open(config_path, "wb") as f:
        tomli_w.dump(config_data, f)


if __name__ == "__main__":
    """Test configuration detection."""
    print_config_info()
