# coding: utf-8



from django.db import connection

from metrics_framework.decorators import metric

INCONSISTENCIES_COUNT_SQL = """
WITH RECURSIVE rec AS (
  SELECT
    parent_id AS ancestor,
    id AS descendant,
    ARRAY[id] AS descendants
  FROM users_group WHERE parent_id IS NOT NULL

  UNION ALL

  SELECT
    parent_id AS ancestor,
    descendant,
    descendants || ancestor AS descendants
  FROM users_group
  JOIN rec ON id = ancestor
  WHERE not (ancestor = any(descendants)) AND parent_id IS NOT NULL
),
self_rec AS (
  SELECT id AS ancestor, id AS descendant, ARRAY[]::integer[] AS descendants
  FROM users_group
),
all_rec AS (
    SELECT * FROM rec
    UNION ALL
    SELECT * FROM self_rec
)
SELECT COUNT(*)
FROM all_rec
LEFT JOIN users_groupclosure closure
    ON ancestor=closure.parent_id AND descendant=closure.child_id
WHERE closure.id IS NULL;
"""


@metric('groups_closure_inconsistent_count')
def compute_groups_closure_inconsistent_count():
    with connection.cursor() as cursor:
        cursor.execute(INCONSISTENCIES_COUNT_SQL)
        value = cursor.fetchone()[0]
    return [{'value': value}]
