from __future__ import annotations

import sqlite3
from typing import Dict, Tuple

from store_settlement.errors import SettlementError

DATE_FMT = "%Y-%m-%d"


def query_service_price(conn: sqlite3.Connection, name: str) -> float:
    row = conn.execute(
        "SELECT price FROM catalog_services WHERE name=? AND status='active'",
        (name,),
    ).fetchone()
    if not row:
        raise SettlementError("service_not_found", {"name": name})
    return float(row["price"] or 0)


def query_service_price_and_duration(conn: sqlite3.Connection, service_name: str) -> Tuple[float, int]:
    row = conn.execute(
        "SELECT price, duration_min FROM catalog_services WHERE name=? AND status='active'",
        (service_name,),
    ).fetchone()
    if not row:
        raise SettlementError("service_not_found", {"name": service_name})
    return float(row["price"] or 0), int(row["duration_min"] or 60)


def query_product_price(conn: sqlite3.Connection, name: str) -> float:
    row = conn.execute(
        "SELECT sale_price FROM catalog_products WHERE name=? AND status='active'",
        (name,),
    ).fetchone()
    if not row:
        raise SettlementError("product_not_found", {"name": name})
    return float(row["sale_price"] or 0)


def query_service_materials(conn: sqlite3.Connection, service_name: str) -> Dict[str, float]:
    svc = conn.execute(
        "SELECT id FROM catalog_services WHERE name=? AND status='active'",
        (service_name,),
    ).fetchone()
    if not svc:
        raise SettlementError("service_not_found", {"name": service_name})
    mats = conn.execute(
        "SELECT product_name, qty FROM catalog_service_materials WHERE service_id=? ORDER BY product_name",
        (svc["id"],),
    ).fetchall()
    return {str(m["product_name"]): float(m["qty"]) for m in mats}
