"""Datenbank-Modul — SQLite-Verwaltung für Kaufvorgänge und Händlerdaten."""

import sqlite3
import json
import uuid
from pathlib import Path
from datetime import datetime, timezone

# Datenbankpfad im Home-Verzeichnis
DB_DIR = Path.home() / ".agent-commerce"
DB_PATH = DB_DIR / "purchases.db"


def _get_connection() -> sqlite3.Connection:
    """Datenbankverbindung herstellen und Tabellen erstellen falls nötig."""
    DB_DIR.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(DB_PATH))
    conn.row_factory = sqlite3.Row

    # Kaufabsichten und Bestellungen
    conn.execute("""
        CREATE TABLE IF NOT EXISTS purchases (
            id TEXT PRIMARY KEY,
            status TEXT NOT NULL DEFAULT 'intent',
            item TEXT NOT NULL,
            quantity INTEGER DEFAULT 1,
            budget_max REAL,
            budget_currency TEXT DEFAULT 'USD',
            delivery_address TEXT,
            delivery_notes TEXT,
            selected_offer TEXT,
            merchant_name TEXT,
            total_price REAL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )
    """)

    # Angebote zu einer Kaufabsicht
    conn.execute("""
        CREATE TABLE IF NOT EXISTS offers (
            id TEXT PRIMARY KEY,
            purchase_id TEXT NOT NULL,
            merchant_name TEXT NOT NULL,
            price REAL NOT NULL,
            currency TEXT DEFAULT 'USD',
            shipping_cost REAL DEFAULT 0,
            delivery_days INTEGER,
            condition TEXT,
            url TEXT,
            notes TEXT,
            created_at TEXT NOT NULL,
            FOREIGN KEY (purchase_id) REFERENCES purchases(id)
        )
    """)

    # Händler-Bewertungen
    conn.execute("""
        CREATE TABLE IF NOT EXISTS merchants (
            name TEXT PRIMARY KEY,
            reliability_score REAL DEFAULT 0.5,
            total_orders INTEGER DEFAULT 0,
            successful_orders INTEGER DEFAULT 0,
            avg_delivery_days REAL,
            last_order_at TEXT,
            notes TEXT
        )
    """)

    conn.commit()
    return conn


def generate_id() -> str:
    """Kurze eindeutige ID generieren."""
    return uuid.uuid4().hex[:12]


def now_iso() -> str:
    """Aktuelle Zeit als ISO-String."""
    return datetime.now(timezone.utc).isoformat()


# --- Kaufvorgänge ---

def create_purchase(item: str, quantity: int = 1,
                    budget_max: float | None = None,
                    budget_currency: str = "USD",
                    delivery_address: str = "",
                    delivery_notes: str = "") -> dict:
    """Neue Kaufabsicht erstellen."""
    conn = _get_connection()
    purchase_id = generate_id()
    now = now_iso()
    conn.execute("""
        INSERT INTO purchases (id, status, item, quantity, budget_max,
                               budget_currency, delivery_address,
                               delivery_notes, created_at, updated_at)
        VALUES (?, 'intent', ?, ?, ?, ?, ?, ?, ?, ?)
    """, (purchase_id, item, quantity, budget_max, budget_currency,
          delivery_address, delivery_notes, now, now))
    conn.commit()
    conn.close()
    return {"id": purchase_id, "status": "intent", "item": item,
            "quantity": quantity, "created_at": now}


def get_purchase(purchase_id: str) -> dict | None:
    """Kaufvorgang laden."""
    conn = _get_connection()
    row = conn.execute(
        "SELECT * FROM purchases WHERE id = ?", (purchase_id,)
    ).fetchone()
    conn.close()
    if row is None:
        return None
    return dict(row)


def update_purchase(purchase_id: str, **kwargs) -> bool:
    """Kaufvorgang aktualisieren."""
    conn = _get_connection()
    kwargs["updated_at"] = now_iso()
    sets = ", ".join(f"{k} = ?" for k in kwargs)
    values = list(kwargs.values()) + [purchase_id]
    cursor = conn.execute(
        f"UPDATE purchases SET {sets} WHERE id = ?", values
    )
    conn.commit()
    conn.close()
    return cursor.rowcount > 0


def list_purchases(status: str | None = None, limit: int = 20) -> list[dict]:
    """Kaufvorgänge auflisten."""
    conn = _get_connection()
    if status:
        rows = conn.execute(
            "SELECT * FROM purchases WHERE status = ? ORDER BY created_at DESC LIMIT ?",
            (status, limit),
        ).fetchall()
    else:
        rows = conn.execute(
            "SELECT * FROM purchases ORDER BY created_at DESC LIMIT ?",
            (limit,),
        ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


# --- Angebote ---

def add_offer(purchase_id: str, merchant_name: str, price: float,
              currency: str = "USD", shipping_cost: float = 0,
              delivery_days: int | None = None, condition: str = "",
              url: str = "", notes: str = "") -> dict:
    """Angebot zu einer Kaufabsicht hinzufügen."""
    conn = _get_connection()
    offer_id = generate_id()
    now = now_iso()
    conn.execute("""
        INSERT INTO offers (id, purchase_id, merchant_name, price, currency,
                            shipping_cost, delivery_days, condition, url,
                            notes, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """, (offer_id, purchase_id, merchant_name, price, currency,
          shipping_cost, delivery_days, condition, url, notes, now))
    conn.commit()
    conn.close()
    return {"id": offer_id, "purchase_id": purchase_id,
            "merchant_name": merchant_name, "price": price}


def get_offers(purchase_id: str) -> list[dict]:
    """Alle Angebote zu einer Kaufabsicht laden."""
    conn = _get_connection()
    rows = conn.execute(
        "SELECT * FROM offers WHERE purchase_id = ? ORDER BY price ASC",
        (purchase_id,),
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


# --- Händler ---

def get_merchant(name: str) -> dict | None:
    """Händler-Daten laden."""
    conn = _get_connection()
    row = conn.execute(
        "SELECT * FROM merchants WHERE name = ?", (name,)
    ).fetchone()
    conn.close()
    if row is None:
        return None
    return dict(row)


def upsert_merchant(name: str, **kwargs):
    """Händler erstellen oder aktualisieren."""
    conn = _get_connection()
    existing = conn.execute(
        "SELECT name FROM merchants WHERE name = ?", (name,)
    ).fetchone()
    if existing:
        sets = ", ".join(f"{k} = ?" for k in kwargs)
        values = list(kwargs.values()) + [name]
        conn.execute(f"UPDATE merchants SET {sets} WHERE name = ?", values)
    else:
        kwargs["name"] = name
        cols = ", ".join(kwargs.keys())
        placeholders = ", ".join(["?"] * len(kwargs))
        conn.execute(
            f"INSERT INTO merchants ({cols}) VALUES ({placeholders})",
            list(kwargs.values()),
        )
    conn.commit()
    conn.close()
