#!/usr/bin/env python3
"""
Inicializace Knowledgebase databáze.
Vytvoří databázi 'knowledgebase' a aplikuje schema.sql.

Spustit jednou:
  python setup_db.py
"""
import os
import sys
import psycopg
from psycopg.rows import dict_row
from pathlib import Path

PG_HOST     = os.getenv("PG_HOST",     "192.168.1.76")
PG_PORT     = int(os.getenv("PG_PORT", "5432"))
PG_USER     = os.getenv("PG_USER",     "vladimir.buzalka")
PG_PASSWORD = os.getenv("PG_PASSWORD", "Vlado7309208104++")

SCHEMA_FILE = Path(__file__).parent / "schema.sql"


def main():
    # ── Připoj se k postgres a vytvoř DB ──
    print("Connecting to postgres...")
    with psycopg.connect(
        host=PG_HOST, port=PG_PORT,
        user=PG_USER, password=PG_PASSWORD,
        dbname="postgres",
        autocommit=True,
    ) as conn:
        exists = conn.execute(
            "SELECT 1 FROM pg_database WHERE datname = 'knowledgebase'"
        ).fetchone()
        if not exists:
            conn.execute("CREATE DATABASE knowledgebase")
            print("Created database 'knowledgebase'")
        else:
            print("Database 'knowledgebase' already exists")

    # ── Aplikuj schema ──
    print("Applying schema...")
    schema = SCHEMA_FILE.read_text(encoding="utf-8")
    with psycopg.connect(
        host=PG_HOST, port=PG_PORT,
        user=PG_USER, password=PG_PASSWORD,
        dbname="knowledgebase",
        autocommit=True,
    ) as conn:
        conn.execute(schema)
    print("Schema applied successfully.")
    print()
    print("Done! Knowledgebase database is ready.")
    print()
    print("Next steps:")
    print("  1. pip install -r requirements.txt")
    print("  2. Optional: set VOYAGE_API_KEY=...")
    print("  3. Add server to Claude Code settings (see below)")
    print()
    print('  "knowledgebase": {')
    print('    "command": "python",')
    print('    "args": ["U:/janssen/Knowledgebase/server.py"],')
    print('    "env": {"VOYAGE_API_KEY": "..."}')
    print('  }')


if __name__ == "__main__":
    main()
