import json
import logging
from agent.database import get_connection, release_connection

logger = logging.getLogger("agent.system_skills.get_workflows")

def run(inputs: dict) -> dict:
    """
    Retrieves the list of workflows or detailed YAML content for a specific workflow.
    """
    workflow_name = inputs.get("workflow_name")
    
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            if workflow_name:
                cur.execute("SELECT yaml_content FROM workflow_definitions WHERE workflow_name = %s", (workflow_name,))
                row = cur.fetchone()
                if row:
                    output = f"Workflow: {workflow_name}\n\nConfiguration (YAML):\n```yaml\n{row[0]}\n```"
                else:
                    output = f"Workflow '{workflow_name}' not found."
            else:
                cur.execute("SELECT workflow_name, description, type, state_count FROM workflow_definitions ORDER BY workflow_name")
                rows = cur.fetchall()
                if rows:
                    lines = ["Available Workflows:"]
                    for r in rows:
                        name, desc, wtype, states = r
                        desc_str = f" - {desc}" if desc else ""
                        lines.append(f"- **{name}** (Type: {wtype}, States: {states}){desc_str}")
                    output = "\n".join(lines)
                else:
                    output = "No workflows found in the registry."
                    
        return {"output": output}
        
    except Exception as e:
        logger.error(f"Error fetching workflows: {e}")
        return {"output": f"Error fetching workflows: {str(e)}"}
    finally:
        release_connection(conn)
