"""Server-Katalog — die Datenbank aller bekannten MCP-Server."""

import json
import sqlite3
from pathlib import Path
from datetime import datetime

# Datenbank im Home-Verzeichnis (persistent zwischen Sessions)
DB_PATH = Path.home() / ".mcp-hub" / "catalog.db"


def _ensure_db():
    """Datenbank und Tabellen erstellen falls nötig."""
    DB_PATH.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(DB_PATH))
    conn.row_factory = sqlite3.Row
    conn.execute("""
        CREATE TABLE IF NOT EXISTS servers (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            description TEXT NOT NULL,
            category TEXT NOT NULL,
            install_command TEXT NOT NULL,
            install_args TEXT DEFAULT '[]',
            github_url TEXT DEFAULT '',
            pypi_url TEXT DEFAULT '',
            author TEXT DEFAULT '',
            tags TEXT DEFAULT '[]',
            requires_api_key INTEGER DEFAULT 0,
            free_tier INTEGER DEFAULT 1,
            added_at TEXT DEFAULT '',
            source TEXT DEFAULT 'builtin'
        )
    """)
    conn.commit()
    return conn


def get_connection():
    """Datenbankverbindung holen, bei Bedarf mit Seed-Daten befüllen."""
    conn = _ensure_db()
    # Prüfen ob Seed-Daten vorhanden
    count = conn.execute("SELECT COUNT(*) FROM servers").fetchone()[0]
    if count == 0:
        _seed_catalog(conn)
    return conn


def _seed_catalog(conn):
    """Katalog mit bekannten MCP-Servern befüllen."""
    servers = [
        # ===== Unsere Server =====
        {
            "id": "solana-mcp-server",
            "name": "Solana MCP Server",
            "description": "Solana blockchain data — wallet balances, token prices, DeFi yields, safety checks, whale tracking, portfolio analysis",
            "category": "Crypto & DeFi",
            "install_command": "uvx",
            "install_args": '["solana-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/solana-mcp-server",
            "pypi_url": "https://pypi.org/project/solana-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["solana", "crypto", "defi", "blockchain", "wallet", "token"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "germany-mcp-server",
            "name": "Germany Open Data MCP Server",
            "description": "German government open data — Destatis statistics, weather (DWD), company registers, energy data",
            "category": "Government & Open Data",
            "install_command": "uvx",
            "install_args": '["germany-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/germany-mcp-server",
            "pypi_url": "https://pypi.org/project/germany-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["germany", "open-data", "statistics", "government", "destatis"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "agriculture-mcp-server",
            "name": "Agriculture MCP Server",
            "description": "Global agriculture data — FAO statistics, soil data, crop yields, food production, NASA weather for farming",
            "category": "Agriculture & Food",
            "install_command": "uvx",
            "install_args": '["agriculture-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/agriculture-mcp-server",
            "pypi_url": "https://pypi.org/project/agriculture-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["agriculture", "farming", "food", "fao", "soil", "crops"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "space-mcp-server",
            "name": "Space MCP Server",
            "description": "NASA & ESA space data — asteroids, Mars rover photos, space weather, astronomy picture of the day, exoplanets",
            "category": "Science & Space",
            "install_command": "uvx",
            "install_args": '["space-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/space-mcp-server",
            "pypi_url": "https://pypi.org/project/space-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["space", "nasa", "astronomy", "mars", "asteroids", "esa"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "aviation-mcp-server",
            "name": "Aviation MCP Server",
            "description": "Aviation data — flight tracking, airport info, airline data, aircraft details, aviation statistics",
            "category": "Transportation",
            "install_command": "uvx",
            "install_args": '["aviation-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/aviation-mcp-server",
            "pypi_url": "https://pypi.org/project/aviation-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["aviation", "flights", "airports", "airlines", "tracking"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "eu-company-mcp-server",
            "name": "EU Company MCP Server",
            "description": "European company data — company search, financial filings, beneficial owners, business registers, LEI lookup",
            "category": "Business & Finance",
            "install_command": "uvx",
            "install_args": '["eu-company-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/eu-company-mcp-server",
            "pypi_url": "https://pypi.org/project/eu-company-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["company", "business", "finance", "eu", "registers", "lei"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "openmeteo-mcp-server",
            "name": "Weather MCP Server",
            "description": "Global weather data — current conditions, 16-day forecast, air quality, historical weather since 1940, marine weather",
            "category": "Weather & Climate",
            "install_command": "uvx",
            "install_args": '["openmeteo-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/weather-mcp-server",
            "pypi_url": "https://pypi.org/project/openmeteo-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["weather", "forecast", "climate", "air-quality", "marine"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "x402-mcp-server",
            "name": "x402 Payment Gateway",
            "description": "Agent-to-agent micropayments via x402 protocol — create paywalls, verify payments, manage invoices for MCP tools",
            "category": "Payments & Infrastructure",
            "install_command": "uvx",
            "install_args": '["x402-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/x402-mcp-server",
            "pypi_url": "https://pypi.org/project/x402-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["payments", "x402", "micropayments", "monetization", "infrastructure"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "agent-memory-mcp-server",
            "name": "Agent Memory Service",
            "description": "Persistent memory for AI agents — store, retrieve and search knowledge across sessions with namespaces",
            "category": "Agent Infrastructure",
            "install_command": "uvx",
            "install_args": '["agent-memory-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/agent-memory-mcp-server",
            "pypi_url": "https://pypi.org/project/agent-memory-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["memory", "persistence", "knowledge", "agents", "storage"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "agent-directory-mcp-server",
            "name": "Agent Directory",
            "description": "Directory of AI agent services — discover, register and rate agent capabilities and MCP servers",
            "category": "Agent Infrastructure",
            "install_command": "uvx",
            "install_args": '["agent-directory-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/agent-directory-mcp-server",
            "pypi_url": "https://pypi.org/project/agent-directory-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["directory", "discovery", "registry", "agents", "marketplace"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "agent-analytics-mcp-server",
            "name": "Agent Analytics",
            "description": "Usage analytics for MCP servers — track tool calls, measure performance, generate reports",
            "category": "Agent Infrastructure",
            "install_command": "uvx",
            "install_args": '["agent-analytics-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/agent-analytics-mcp-server",
            "pypi_url": "https://pypi.org/project/agent-analytics-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["analytics", "monitoring", "tracking", "performance", "reports"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "agent-reputation-mcp-server",
            "name": "Agent Reputation System",
            "description": "Trust and reputation scoring for AI agents — rate interactions, build trust scores, verify reliability",
            "category": "Agent Infrastructure",
            "install_command": "uvx",
            "install_args": '["agent-reputation-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/agent-reputation-mcp-server",
            "pypi_url": "https://pypi.org/project/agent-reputation-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["reputation", "trust", "rating", "verification", "agents"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "agent-workflow-mcp-server",
            "name": "Agent Workflow Templates",
            "description": "Reusable workflow templates for AI agents — share, discover and execute multi-step workflows",
            "category": "Agent Infrastructure",
            "install_command": "uvx",
            "install_args": '["agent-workflow-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/agent-workflow-mcp-server",
            "pypi_url": "https://pypi.org/project/agent-workflow-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["workflows", "templates", "automation", "pipelines", "agents"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "cybersecurity-mcp-server",
            "name": "Cybersecurity MCP Server",
            "description": "Security intelligence — CVE database, threat feeds, IP reputation, domain analysis, vulnerability scanning",
            "category": "Security",
            "install_command": "uvx",
            "install_args": '["cybersecurity-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/cybersecurity-mcp-server",
            "pypi_url": "https://pypi.org/project/cybersecurity-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["security", "cve", "threats", "vulnerabilities", "cybersecurity"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "medical-data-mcp-server",
            "name": "Medical Data MCP Server",
            "description": "Health and medical data — WHO statistics, drug information, disease data, clinical trials, ICD codes",
            "category": "Health & Medical",
            "install_command": "uvx",
            "install_args": '["medical-data-mcp-server"]',
            "github_url": "https://github.com/AiAgentKarl/health-mcp-server",
            "pypi_url": "https://pypi.org/project/medical-data-mcp-server/",
            "author": "AiAgentKarl",
            "tags": '["health", "medical", "who", "drugs", "diseases", "clinical-trials"]',
            "requires_api_key": 0, "free_tier": 1,
        },

        # ===== Populäre Third-Party Server =====
        {
            "id": "mcp-server-github",
            "name": "GitHub MCP Server",
            "description": "Official GitHub integration — repos, issues, PRs, code search, actions, gists",
            "category": "Developer Tools",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-github"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["github", "git", "repos", "issues", "pull-requests", "code"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-filesystem",
            "name": "Filesystem MCP Server",
            "description": "Official filesystem access — read, write, search files and directories",
            "category": "Developer Tools",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-filesystem"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["filesystem", "files", "directories", "read", "write"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-postgres",
            "name": "PostgreSQL MCP Server",
            "description": "Official PostgreSQL integration — query databases, inspect schemas, manage tables",
            "category": "Databases",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-postgres"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["postgres", "database", "sql", "query"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-sqlite",
            "name": "SQLite MCP Server",
            "description": "Official SQLite integration — query local databases, create tables, analyze data",
            "category": "Databases",
            "install_command": "uvx",
            "install_args": '["mcp-server-sqlite"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["sqlite", "database", "sql", "local"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-brave-search",
            "name": "Brave Search MCP Server",
            "description": "Web search via Brave Search API — search the web, get results with snippets",
            "category": "Search & Web",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-brave-search"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["search", "web", "brave", "internet"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-puppeteer",
            "name": "Puppeteer MCP Server",
            "description": "Browser automation — navigate websites, take screenshots, interact with web pages",
            "category": "Browser & Automation",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-puppeteer"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["browser", "puppeteer", "automation", "screenshots", "web"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-slack",
            "name": "Slack MCP Server",
            "description": "Official Slack integration — send messages, manage channels, search conversations",
            "category": "Communication",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-slack"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["slack", "messaging", "chat", "communication", "teams"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-google-maps",
            "name": "Google Maps MCP Server",
            "description": "Google Maps integration — geocoding, directions, places search, distance calculation",
            "category": "Maps & Location",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-google-maps"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["maps", "google", "geocoding", "directions", "places"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-memory",
            "name": "Memory MCP Server (Anthropic)",
            "description": "Official knowledge graph memory — store and retrieve structured knowledge persistently",
            "category": "Agent Infrastructure",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-memory"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["memory", "knowledge-graph", "persistence", "storage"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-fetch",
            "name": "Fetch MCP Server",
            "description": "Official web fetching — retrieve and parse web pages, extract content as markdown",
            "category": "Search & Web",
            "install_command": "uvx",
            "install_args": '["mcp-server-fetch"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["fetch", "web", "scraping", "markdown", "content"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-stripe",
            "name": "Stripe MCP Server",
            "description": "Stripe payment integration — manage customers, invoices, subscriptions, payment intents",
            "category": "Payments & Infrastructure",
            "install_command": "npx",
            "install_args": '["-y", "@stripe/mcp"]',
            "github_url": "https://github.com/stripe/agent-toolkit",
            "author": "Stripe",
            "tags": '["stripe", "payments", "billing", "subscriptions", "invoices"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-notion",
            "name": "Notion MCP Server",
            "description": "Notion workspace integration — search, read and update pages, databases and blocks",
            "category": "Productivity",
            "install_command": "npx",
            "install_args": '["-y", "@notionhq/mcp-server"]',
            "github_url": "https://github.com/notionhq/mcp-server",
            "author": "Notion",
            "tags": '["notion", "docs", "wiki", "databases", "workspace"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-linear",
            "name": "Linear MCP Server",
            "description": "Linear project management — issues, projects, teams, cycles, labels",
            "category": "Productivity",
            "install_command": "npx",
            "install_args": '["-y", "@linear/mcp-server"]',
            "github_url": "https://github.com/linear/linear-mcp-server",
            "author": "Linear",
            "tags": '["linear", "issues", "project-management", "tasks", "agile"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-docker",
            "name": "Docker MCP Server",
            "description": "Docker container management — list, start, stop containers, view logs, manage images",
            "category": "DevOps",
            "install_command": "npx",
            "install_args": '["-y", "@docker/mcp-server"]',
            "github_url": "https://github.com/docker/mcp-server",
            "author": "Docker",
            "tags": '["docker", "containers", "devops", "images", "deployment"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-sentry",
            "name": "Sentry MCP Server",
            "description": "Sentry error tracking — view issues, stack traces, release health, performance data",
            "category": "Developer Tools",
            "install_command": "npx",
            "install_args": '["-y", "@sentry/mcp-server"]',
            "github_url": "https://github.com/getsentry/sentry-mcp",
            "author": "Sentry",
            "tags": '["sentry", "errors", "monitoring", "debugging", "performance"]',
            "requires_api_key": 1, "free_tier": 1,
        },
        {
            "id": "mcp-server-time",
            "name": "Time MCP Server",
            "description": "Time and timezone tools — current time, timezone conversion, date calculations",
            "category": "Utilities",
            "install_command": "uvx",
            "install_args": '["mcp-server-time"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["time", "timezone", "date", "clock", "conversion"]',
            "requires_api_key": 0, "free_tier": 1,
        },
        {
            "id": "mcp-server-everything",
            "name": "Everything MCP Server",
            "description": "Reference/test server that demonstrates all MCP features — prompts, resources, tools, sampling",
            "category": "Developer Tools",
            "install_command": "npx",
            "install_args": '["-y", "@modelcontextprotocol/server-everything"]',
            "github_url": "https://github.com/modelcontextprotocol/servers",
            "author": "Anthropic",
            "tags": '["reference", "testing", "demo", "example"]',
            "requires_api_key": 0, "free_tier": 1,
        },
    ]

    now = datetime.utcnow().isoformat()
    for s in servers:
        s["added_at"] = now
        s["source"] = "builtin"
        s.setdefault("pypi_url", "")
        conn.execute("""
            INSERT OR IGNORE INTO servers
            (id, name, description, category, install_command, install_args,
             github_url, pypi_url, author, tags, requires_api_key, free_tier,
             added_at, source)
            VALUES (:id, :name, :description, :category, :install_command,
                    :install_args, :github_url, :pypi_url, :author, :tags,
                    :requires_api_key, :free_tier, :added_at, :source)
        """, s)
    conn.commit()
