"""
Brynq Templates
Allows users to save, load, export, and import their favorite orchestration workflows.
"""

import json
from pathlib import Path
from typing import Dict, Any, List

def _templates_dir(data_dir: Path) -> Path:
    d = data_dir / "templates"
    d.mkdir(parents=True, exist_ok=True)
    return d

def save_chain_template(data_dir: Path, name: str, steps: List[Dict[str, Any]]) -> str:
    """Save a workflow/chain as a template."""
    tdir = _templates_dir(data_dir)
    template = {
        "name": name,
        "type": "chain",
        "steps": steps
    }
    path = tdir / f"{name}.json"
    path.write_text(json.dumps(template, indent=2), encoding="utf-8")
    return str(path)

def load_chain_template(data_dir: Path, name: str) -> Dict[str, Any]:
    """Load a specific template by name."""
    path = _templates_dir(data_dir) / f"{name}.json"
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}

def list_templates(data_dir: Path) -> List[str]:
    """List all saved templates."""
    tdir = _templates_dir(data_dir)
    return [p.stem for p in tdir.glob("*.json")]

def export_template(data_dir: Path, name: str, export_path: str) -> bool:
    """Export a template to a specific path."""
    template = load_chain_template(data_dir, name)
    if not template:
        return False
    try:
        Path(export_path).write_text(json.dumps(template, indent=2), encoding="utf-8")
        return True
    except Exception:
        return False

def import_template(data_dir: Path, filepath: str) -> str:
    """Import a template from a file."""
    path = Path(filepath)
    if not path.exists():
        return ""
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        name = data.get("name", path.stem)
        save_chain_template(data_dir, name, data.get("steps", []))
        return name
    except Exception:
        return ""
