"""Tests for benchmark_format_compliance sub-score."""
from __future__ import annotations

from pipeline.coverage import benchmark_format_compliance


def _build_schema(business_tables, cfg_tables):
    return {
        "schema_name": "demo",
        "menus": [
            {
                "menu_id": 1, "menu_name": "Ops", "sequence_number": 1,
                "description": "ops",
                "submenus": [
                    {"submenu_id": 101, "submenu_name": "x",
                     "sequence_number": 1, "description": "x",
                     "tables": business_tables},
                ],
            },
            {
                "menu_id": 18, "menu_name": "Configuration", "sequence_number": 18,
                "description": "config",
                "submenus": [
                    {"submenu_id": 1801, "submenu_name": "Config",
                     "sequence_number": 1, "description": "x",
                     "tables": cfg_tables},
                ],
            },
        ],
    }


def test_perfect_compliance_scores_high():
    biz = [{
        "table_name": "orders",
        "comment": "x",
        "columns": [
            {"name": "id", "type": "SERIAL", "constraints": "PRIMARY KEY"},
            {"name": "status_id", "type": "INT"},
            {"name": "created_at", "type": "TIMESTAMP"},
            {"name": "updated_at", "type": "TIMESTAMP"},
            {"name": "is_active", "type": "BOOLEAN"},
        ],
        "foreign_keys": [{"column": "status_id",
                          "references": "demo.cfg_order_status(cfg_order_status_id)"}],
    }]
    cfg = [{
        "table_name": "cfg_order_status",
        "comment": "x",
        "columns": [{"name": "cfg_order_status_id", "type": "SERIAL",
                     "constraints": "PRIMARY KEY"}],
        "foreign_keys": [],
    }]
    s = _build_schema(biz, cfg)
    sql = """
COMMENT ON TABLE demo.orders IS 'x';
COMMENT ON TABLE demo.cfg_order_status IS 'x';
CREATE INDEX idx_orders_status_id ON demo.orders(status_id);
CREATE INDEX idx_orders_created_at ON demo.orders(created_at);
CREATE INDEX idx_orders_updated_at ON demo.orders(updated_at);
CHECK (qty >= 0)
CHECK (price >= 0)
CHECK (end_date >= start_date)
CHECK (email LIKE '%@%')
CHECK (pct BETWEEN 0 AND 100)
"""
    score, detail = benchmark_format_compliance(s, sql)
    assert score >= 90, f"perfect schema should score >= 90, got {score}"
    assert detail["fk_density_score"] == 100.0
    assert detail["audit_score"] == 100.0
    assert detail["check_score"] == 100.0


def test_no_cfg_tables_doesnt_penalize_fk_density():
    """Schemas without cfg_* tables get full FK-density credit (vacuously true)."""
    biz = [{
        "table_name": "items",
        "comment": "x",
        "columns": [{"name": "id", "type": "SERIAL", "constraints": "PRIMARY KEY"}],
        "foreign_keys": [],
    }]
    s = _build_schema(biz, [])
    score, detail = benchmark_format_compliance(s, "")
    assert detail["fk_density_score"] == 100.0


def test_missing_indexes_drops_idx_score():
    biz = [{
        "table_name": "orders",
        "comment": "x",
        "columns": [{"name": "id", "type": "SERIAL", "constraints": "PRIMARY KEY"}],
        "foreign_keys": [],
    }]
    s = _build_schema(biz, [])
    score, detail = benchmark_format_compliance(s, "")
    assert detail["idx_score"] == 0.0


def test_missing_audit_cols_lowers_score():
    biz = [{
        "table_name": "orders",
        "comment": "x",
        "columns": [{"name": "id", "type": "SERIAL"}],  # no audit cols
        "foreign_keys": [],
    }]
    s = _build_schema(biz, [])
    score, detail = benchmark_format_compliance(s, "")
    assert detail["audit_score"] == 0.0


def test_check_score_thresholds():
    biz = [{
        "table_name": "orders", "comment": "x",
        "columns": [], "foreign_keys": [],
    }]
    s = _build_schema(biz, [])

    # 0 CHECKs
    _, d = benchmark_format_compliance(s, "")
    assert d["check_score"] == 0

    # 1 CHECK = 60 (50 + 1*10)
    _, d = benchmark_format_compliance(s, "CHECK (qty >= 0)")
    assert 50 < d["check_score"] < 70

    # 5+ CHECKs = 100
    sql_5 = "\n".join(["CHECK (a > 0)"] * 5)
    _, d = benchmark_format_compliance(s, sql_5)
    assert d["check_score"] == 100


def test_inline_references_counted_as_fk():
    """Column with inline REFERENCES cfg_X counts toward FK density."""
    biz = [{
        "table_name": "orders",
        "comment": "x",
        "columns": [
            {"name": "status_id", "type": "INT",
             "constraints": "NOT NULL REFERENCES demo.cfg_order_status(id)"},
        ],
        "foreign_keys": [],
    }]
    cfg = [{
        "table_name": "cfg_order_status",
        "comment": "x",
        "columns": [{"name": "id", "type": "SERIAL", "constraints": "PRIMARY KEY"}],
        "foreign_keys": [],
    }]
    s = _build_schema(biz, cfg)
    score, detail = benchmark_format_compliance(s, "")
    assert detail["raw"]["fk_to_cfg"] >= 1
    assert detail["fk_density_score"] >= 50


def test_empty_schema():
    score, detail = benchmark_format_compliance({}, "")
    # Empty schema = no business tables = trivially compliant on most components
    assert score >= 0


def test_non_dict_schema_returns_zero():
    score, detail = benchmark_format_compliance(None, "")
    assert score == 0.0
