"""GEO AgentKit Server 启动入口

工厂函数 create_geo_app() 使用 agentkit.yaml 统一配置，
初始化 LLM Gateway、Tool Registry、Skill Registry，然后创建 FastAPI 应用。

使用方式：
    uvicorn configs.geo_server:create_geo_app --factory --host 0.0.0.0 --port 8001
"""

from __future__ import annotations

import logging
import os

from fastapi import FastAPI

from agentkit.server.app import _build_llm_gateway, create_app
from agentkit.server.config import ServerConfig, find_config_path, load_config_with_dotenv
from agentkit.skills.loader import SkillLoader
from agentkit.skills.registry import SkillRegistry
from agentkit.tools.registry import ToolRegistry

logger = logging.getLogger(__name__)

# ─── 配置路径 ───

CONFIGS_DIR = os.path.dirname(os.path.abspath(__file__))
SKILLS_DIR = os.path.join(CONFIGS_DIR, "skills")


def _load_server_config() -> ServerConfig:
    """Load ServerConfig from agentkit.yaml with .env resolution."""
    config_path = find_config_path()
    if config_path:
        return load_config_with_dotenv(config_path)
    raise FileNotFoundError("agentkit.yaml not found (searched CWD and ~/.agentkit/)")


def _init_tool_registry() -> ToolRegistry:
    """初始化 Tool Registry 并注册 GEO Tools"""
    registry = ToolRegistry()
    from configs.geo_tools import register_geo_tools

    register_geo_tools(registry)
    return registry


def _init_skill_registry(tool_registry: ToolRegistry) -> SkillRegistry:
    """初始化 Skill Registry 并从 configs/skills/ 目录加载"""
    registry = SkillRegistry()
    loader = SkillLoader(registry, tool_registry)
    skills = loader.load_from_directory(SKILLS_DIR)
    logger.info(f"Loaded {len(skills)} skills from {SKILLS_DIR}")
    return registry


def create_geo_app() -> FastAPI:
    """GEO AgentKit Server FastAPI 工厂函数"""
    config = _load_server_config()
    llm_gateway = _build_llm_gateway(config)
    tool_registry = _init_tool_registry()
    skill_registry = _init_skill_registry(tool_registry)

    app = create_app(
        llm_gateway=llm_gateway,
        skill_registry=skill_registry,
        tool_registry=tool_registry,
    )
    app.title = "GEO AgentKit Server"

    logger.info(
        f"GEO AgentKit Server initialized: {len(skill_registry.list_skills())} skills, "
        f"{len(tool_registry.list_tools())} tools"
    )

    return app
