"""Reproduce the editorial SQL checks. No connections except SQLite :memory:."""
import json
import platform
from pathlib import Path
import sqlite3

ROOT = Path(__file__).resolve().parent
FIXTURES = (ROOT / "fixtures.sql").read_text(encoding="utf-8")
QUERY = (ROOT / "query.sql").read_text(encoding="utf-8")
NAIVE = """
SELECT c.id, COUNT(o.id), COALESCE(SUM(o.amount), 0),
       SUM(CASE WHEN o.id IS NOT NULL AND o.amount IS NULL THEN 1 ELSE 0 END)
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
LEFT JOIN order_items i ON i.order_id = o.id
GROUP BY c.id ORDER BY c.id;
"""
EXPECTED = [(1, 2, 200, 0), (2, 1, 0, 1), (3, 0, 0, 0), (4, 1, 50, 0)]

def connect(empty=None):
    db = sqlite3.connect(":memory:")
    db.executescript(FIXTURES)
    if empty:
        db.execute("DELETE FROM order_items")
        db.execute("DELETE FROM orders")
        if empty == "all":
            db.execute("DELETE FROM customers")
    db.execute("PRAGMA query_only = ON")
    return db

def require(condition, message):
    if not condition:
        raise AssertionError(message)

with connect() as db:
    red = db.execute(NAIVE).fetchall()
    green = db.execute(QUERY).fetchall()
    require(red != EXPECTED and red[0] == (1, 3, 300, 0), "Fanout was not reproduced")
    require(green == EXPECTED, "Corrected SELECT differs from expected rows")
    require(len({row[0] for row in green}) == len(green), "Duplicate output keys")
    require(sum(row[2] for row in green) == 250, "Known amount total differs")
    duplicate_result_keys = db.execute("""
        SELECT o.id, COUNT(*) FROM orders o
        LEFT JOIN order_items i ON i.order_id = o.id
        GROUP BY o.id HAVING COUNT(*) > 1
    """).fetchall()
    require(duplicate_result_keys == [(101, 2)], "Repeated joined order key not detected")
    duplicate_items = db.execute("""
        SELECT order_id, sku, quantity, COUNT(*) FROM order_items
        GROUP BY order_id, sku, quantity HAVING COUNT(*) > 1
    """).fetchall()
    require(duplicate_items == [(101, "A", 1, 2)], "Duplicate fixture not detected")
    null_wrong = db.execute("SELECT id FROM orders WHERE amount = NULL").fetchall()
    null_right = db.execute("SELECT id FROM orders WHERE amount IS NULL").fetchall()
    require(null_wrong == [] and null_right == [(103,)], "NULL behavior differs")
    distinct_wrong = db.execute("SELECT SUM(DISTINCT amount) FROM orders WHERE customer_id = 1").fetchone()[0]
    require(distinct_wrong == 100, "SUM(DISTINCT) counterexample differs")
with connect("orders") as db:
    empty_orders = db.execute(QUERY).fetchall()
    require(empty_orders == [(i, 0, 0, 0) for i in range(1, 5)], "Customers lost with no orders")
with connect("all") as db:
    empty_all = db.execute(QUERY).fetchall()
    require(empty_all == [], "Empty input should return no customers")
print(json.dumps({
    "status": "PASS", "check_origin": "editorial local execution; not Iskra",
    "runtime": {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version,
                "database": ":memory:", "dialect": "SQLite"},
    "columns": ["customer_id", "order_count", "known_revenue", "unknown_amounts"],
    "red_naive_join": red, "green_corrected_select": green,
    "expected_rows": EXPECTED, "known_amount_total": 250,
    "duplicate_items": duplicate_items, "duplicate_joined_result_keys": duplicate_result_keys,
    "null_equals_wrong": null_wrong,
    "null_is_correct": null_right, "sum_distinct_wrong": distinct_wrong,
    "empty_orders": empty_orders, "empty_all": empty_all,
    "iskra_run": "not executed", "production_database_connections": 0,
    "limits": ["PostgreSQL and SQL Server not executed", "production data not checked",
               "EXPLAIN and performance not checked", "business duplicate policy needs confirmation"]
}, ensure_ascii=False, indent=2))
