#!/usr/bin/env python3
"""Operational health check for ClientFlow deployments."""
from __future__ import annotations

import json
import os
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))
os.chdir(PROJECT_ROOT)
from sqlalchemy import text

from app.config import settings
from app.db import engine


def scalar(sql: str, **params):
    with engine.begin() as conn:
        return conn.execute(text(sql), params).scalar()


def rows(sql: str, **params):
    with engine.begin() as conn:
        return [dict(r) for r in conn.execute(text(sql), params).mappings().all()]


def main() -> int:
    result = {
        "app": settings.app_name,
        "env": settings.env,
        "database_ok": False,
        "jasmin_enabled": bool(settings.jasmin_enabled),
        "packlink_enabled": bool(settings.packlink_enabled),
        "outbox": {},
        "documents": {},
        "warnings": [],
    }

    try:
        result["database_ok"] = bool(scalar("SELECT 1"))
    except Exception as exc:
        result["warnings"].append(f"database_error: {exc}")
        print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
        return 2

    for row in rows("""
        SELECT target_system, status, count(*)::int AS total
        FROM integration_outbox
        GROUP BY target_system, status
        ORDER BY target_system, status
    """):
        result["outbox"].setdefault(row["target_system"], {})[row["status"]] = row["total"]

    for row in rows("""
        SELECT document_kind, status, count(*)::int AS total
        FROM commercial_documents
        GROUP BY document_kind, status
        ORDER BY document_kind, status
    """):
        result["documents"].setdefault(row["document_kind"], {})[row["status"]] = row["total"]

    missing_jasmin = scalar("""
        SELECT count(*)
        FROM products
        WHERE active = TRUE
          AND (jasmin_sales_item IS NULL OR jasmin_sales_item = '')
    """)
    if missing_jasmin:
        result["warnings"].append(f"active_products_without_jasmin_sales_item={missing_jasmin}")

    failed_outbox = scalar("SELECT count(*) FROM integration_outbox WHERE status = 'failed'")
    if failed_outbox:
        result["warnings"].append(f"failed_outbox_items={failed_outbox}")

    print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
    return 1 if result["warnings"] else 0


if __name__ == "__main__":
    raise SystemExit(main())
