# Hermes Dispatch Tool — Answer Engine Citation Tracker
# Source: https://hermesdispatch.dev/tools/answer-engine-citation-tracker/
# Description: Generate test links for Perplexity, ChatGPT, Gemini, and Copilot to check if a page is cited.
# License: MIT (generated by hermesdispatch.dev)
#
# INSTALL:
#   1. Save this file as ~/.hermes/hermes-agent/tools/answer_engine_citation_tracker.py
#   2. Restart Hermes or run /reset in a session
#
# MANUAL REGISTRY:
#   from tools.answer_engine_citation_tracker import register
#   register()

import json

def _ok(result):
    return json.dumps({"success": True, "data": result}, indent=2)

def _err(message):
    return json.dumps({"success": False, "error": message}, indent=2)

TOOL_NAME = "answer_engine_citation_tracker"
TOOLSET = "seo"

SCHEMA = {
    "type": "function",
    "function": {
        "name": TOOL_NAME,
        "description": "Generate answer-engine citation test links for a URL and query. Returns Perplexity, ChatGPT, Gemini, and Copilot URLs an agent can open to verify whether a page is cited.",
        "parameters": {
            "type": "object",
            "properties": {
                "url": {"type": "string", "description": "Page URL to monitor for citations."},
                "query": {"type": "string", "description": "Query to test on each answer engine."}
            },
            "required": ["url", "query"]
        }
    }
}

def citation_test_links(url, query):
    from urllib.parse import quote
    encoded = quote(query)
    return _ok({
        "target_url": url,
        "query": query,
        "test_links": {
            "perplexity": f"https://www.perplexity.ai/search?q={encoded}",
            "chatgpt": f"https://chat.openai.com/?q={encoded}",
            "gemini": f"https://gemini.google.com/app?q={encoded}",
            "copilot": f"https://copilot.microsoft.com/?q={encoded}",
        },
        "note": "Open each link and check whether the target_url appears in the answer sources.",
    })

def HANDLER(args):
    try:
        return citation_test_links(args.get("url", ""), args.get("query", ""))
    except Exception as e:
        return _err(str(e))

def register():
    try:
        from tools.registry import registry
        registry.register(name=TOOL_NAME, toolset=TOOLSET, schema=SCHEMA, handler=HANDLER)
    except ImportError:
        print("Hermes registry not found; skipping manual registration.")

if __name__ == "__main__":
    print(HANDLER({"url": "https://hermesdispatch.dev", "query": "best GPU for local LLM"}))
