"""
api.v1.templates_api — Agent template discovery from agentexample/.

GET  /api/v1/templates            List all available templates
GET  /api/v1/templates/{id}       Get full template config (for pre-filling the create form)
"""
from __future__ import annotations
import os
from typing import Optional

import yaml
from fastapi import APIRouter, Depends, HTTPException

from agentpaas.api.deps import get_tenant
from agentpaas.api.middleware.auth import TenantContext

router = APIRouter(prefix="/templates", tags=["templates"])

_YAML_FILENAMES = ("agent-config.yml", "orchestrator.yml", "agent-config.yaml")


def _find_agentexample_dir() -> str:
    candidate = os.path.join(os.getcwd(), "agentexample")
    if os.path.isdir(candidate):
        return candidate
    here = os.path.dirname(os.path.abspath(__file__))
    for _ in range(6):
        c = os.path.join(here, "agentexample")
        if os.path.isdir(c):
            return c
        here = os.path.dirname(here)
    return ""


def _load_template(dir_path: str) -> Optional[dict]:
    for fname in _YAML_FILENAMES:
        path = os.path.join(dir_path, fname)
        if os.path.exists(path):
            try:
                with open(path, encoding="utf-8") as f:
                    return yaml.safe_load(f)
            except Exception:
                return None
    return None


def _summary(cfg: dict, dir_name: str) -> dict:
    model = cfg.get("model") or {}
    desc = cfg.get("description", "")
    if isinstance(desc, str):
        desc = desc.strip().replace("\n", " ")
    return {
        "id": dir_name,
        "name": cfg.get("name") or cfg.get("agentId") or dir_name,
        "description": desc[:200] if desc else "",
        "type": cfg.get("type", "react"),
        "provider": model.get("provider", ""),
        "model": model.get("name", ""),
        "has_tools": bool(cfg.get("mcp", {}).get("localTools")),
        "has_memory": bool(cfg.get("memory", {}).get("enabled")),
    }


@router.get("")
async def list_templates(_tenant: TenantContext = Depends(get_tenant)):
    base = _find_agentexample_dir()
    if not base:
        return {"templates": []}

    templates = []
    for name in sorted(os.listdir(base)):
        dir_path = os.path.join(base, name)
        if not os.path.isdir(dir_path) or name.startswith("_"):
            continue
        cfg = _load_template(dir_path)
        if cfg and isinstance(cfg, dict):
            templates.append(_summary(cfg, name))

    return {"templates": templates}


@router.get("/{template_id}")
async def get_template(template_id: str, _tenant: TenantContext = Depends(get_tenant)):
    if ".." in template_id or "/" in template_id:
        raise HTTPException(400, "invalid template id")

    base = _find_agentexample_dir()
    if not base:
        raise HTTPException(404, "agentexample directory not found")

    dir_path = os.path.join(base, template_id)
    if not os.path.isdir(dir_path):
        raise HTTPException(404, "template not found")

    cfg = _load_template(dir_path)
    if cfg is None:
        raise HTTPException(404, "no config file in template")

    return {"template": cfg, "summary": _summary(cfg, template_id)}
