"""registry.store — Agent CRUD persistence + search."""
from __future__ import annotations
import json
from typing import Optional, List, Dict, Any
from agentpaas.db.session import get_db


def get_agent(agent_id: str, tenant_id: str) -> Optional[Dict]:
    db = get_db()
    agent = db.fetchone("SELECT * FROM agents WHERE id=? AND tenant_id=? AND status='active'", (agent_id, tenant_id))
    if agent:
        agent["tags"] = json.loads(agent.get("tags", "[]"))
    return agent

def get_agent_config(agent_id: str, version: int) -> Optional[Dict]:
    db = get_db()
    v = db.fetchone("SELECT config FROM agent_versions WHERE agent_id=? AND version=?", (agent_id, version))
    return json.loads(v["config"]) if v else None

def search_agents(tenant_id: str, tag: str = None, name: str = None) -> List[Dict]:
    db = get_db()
    sql = "SELECT * FROM agents WHERE tenant_id=? AND status='active'"
    params = [tenant_id]
    if tag:
        sql += " AND tags LIKE ?"
        params.append(f'%"{tag}"%')
    if name:
        sql += " AND name LIKE ?"
        params.append(f"%{name}%")
    return db.fetchall(sql + " ORDER BY updated_at DESC", tuple(params))
