"""Measure one checked-out dbt project: models, tests per model, key tests, source freshness, tests in CI.

The definitions are protocol-r1.json's. This reads files only; it never runs the project.

measure(repo_dir, project_path) -> dict of counts (no file contents, no names).
Usage: python3 -B measure.py <repo_dir> <path/to/dbt_project.yml>
"""
import glob
import json
import os
import posixpath
import re
import sys

import yaml

REF = re.compile(r"""\bref\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"])?""")
GENERIC_DEF = re.compile(r"{%-?\s*test\s+\w+\s*\(")
JINJA_EXPR = re.compile(r"{{.*?}}", re.S)
JINJA_STMT = re.compile(r"{%.*?%}", re.S)
CI_TEST = re.compile(r"\bdbt(?:\s+--?[\w-]+(?:=\S+)?)*\s+(?:build|test)\b")
CI_ANY = re.compile(r"\bdbt(?:\s+--?[\w-]+(?:=\S+)?)*\s+(?:run|build|test|seed|snapshot|compile|deps|parse|ls|list|docs|source)\b")
PR_TRIGGERS = {"pull_request", "pull_request_target", "merge_group"}
OTHER_CI = re.compile(r"^(?:Jenkinsfile|\.circleci/config\.ya?ml|azure-pipelines[\w.-]*\.ya?ml|bitbucket-pipelines\.ya?ml|"
                      r"\.drone\.ya?ml|\.buildkite/[\w.-]+\.ya?ml|\.[a-z0-9]+-ci\.ya?ml)$")
KEY_SINGLE = {"unique_combination_of_columns", "primary_key"}
NON_TEST_KEYS = {"name", "config", "description", "meta", "tags", "severity", "where", "arguments"}


def load_yaml(text):
    """(documents, ok). Jinja in YAML is replaced before trying again."""
    for attempt in (text, JINJA_STMT.sub("", JINJA_EXPR.sub("JINJA", text))):
        try:
            return [d for d in yaml.safe_load_all(attempt) if d is not None], True
        except Exception:
            continue
    return [], False


def read(path):
    try:
        with open(path, encoding="utf-8", errors="replace") as f:
            return f.read()
    except OSError:
        return ""


def test_name(t):
    if isinstance(t, str):
        return t.split(".")[-1].strip()
    if isinstance(t, dict):
        if isinstance(t.get("test_name"), str):
            return t["test_name"].split(".")[-1]
        keys = [k for k in t if isinstance(k, str) and k not in NON_TEST_KEYS]
        if keys:
            return keys[0].split(".")[-1]
    return None


def tests_of(node):
    if not isinstance(node, dict):
        return []
    out = []
    for key in ("tests", "data_tests"):
        v = node.get(key)
        if isinstance(v, list):
            out += [n for n in (test_name(t) for t in v) if n]
    return out


def has_freshness(node):
    if not isinstance(node, dict):
        return False
    if node.get("freshness") is not None and "freshness" in node:
        return True
    cfg = node.get("config")
    return isinstance(cfg, dict) and cfg.get("freshness") is not None and "freshness" in cfg


def project_freshness(cfg):
    """+freshness or freshness under sources: in dbt_project.yml, at any depth, not null"""
    stack = [cfg.get("sources")] if isinstance(cfg, dict) else []
    while stack:
        x = stack.pop()
        if isinstance(x, dict):
            for k, v in x.items():
                if k in ("+freshness", "freshness") and v is not None:
                    return True
                stack.append(v)
    return False


def triggers(doc):
    on = doc.get("on", doc.get(True))
    if isinstance(on, str):
        return {on}
    if isinstance(on, list):
        return {str(x) for x in on}
    if isinstance(on, dict):
        return {str(k) for k in on}
    return set()


def strip_comments(text):
    return "\n".join(l for l in text.splitlines() if not l.lstrip().startswith("#"))


def ci(repo_dir):
    res = {"workflows": 0, "ci_tests_before_merge": False, "ci_tests_push_only": False, "ci_runs_dbt": False,
           "other_ci_tests": False, "workflow_parse_errors": 0}
    wf = sorted(glob.glob(os.path.join(repo_dir, ".github", "workflows", "*.yml")) +
                glob.glob(os.path.join(repo_dir, ".github", "workflows", "*.yaml")))
    res["workflows"] = len(wf)
    for p in wf:
        text = strip_comments(read(p))
        docs, ok = load_yaml(text)
        if not ok:
            res["workflow_parse_errors"] += 1
        trig = set()
        for d in docs:
            if isinstance(d, dict):
                trig |= triggers(d)
        runs_tests = bool(CI_TEST.search(text))
        if CI_ANY.search(text):
            res["ci_runs_dbt"] = True
        if runs_tests and trig & PR_TRIGGERS:
            res["ci_tests_before_merge"] = True
        elif runs_tests and "push" in trig:
            res["ci_tests_push_only"] = True
    for root, dirs, files in os.walk(repo_dir):
        rel_root = os.path.relpath(root, repo_dir)
        dirs[:] = [d for d in dirs if d in (".circleci", ".buildkite")] if rel_root == "." else []
        for fn in files:
            rel = fn if rel_root == "." else f"{rel_root}/{fn}"
            if OTHER_CI.match(rel) and CI_TEST.search(strip_comments(read(os.path.join(repo_dir, rel)))):
                res["other_ci_tests"] = True
    if res["ci_tests_before_merge"]:
        res["ci_tests_push_only"] = False
    return res


def measure(repo_dir, project_path):
    pdir = os.path.join(repo_dir, posixpath.dirname(project_path))
    cfg_docs, cfg_ok = load_yaml(read(os.path.join(repo_dir, project_path)))
    cfg = cfg_docs[0] if cfg_docs and isinstance(cfg_docs[0], dict) else {}

    def paths(keys, default):
        for k in keys:
            v = cfg.get(k)
            if isinstance(v, str):
                v = [v]
            if isinstance(v, list) and v:
                v = [str(x).strip("/") for x in v if isinstance(x, (str, int)) and "{{" not in str(x)]
                if v:
                    return v
        return default

    model_dirs = paths(("model-paths", "source-paths"), ["models"])
    test_dirs = paths(("test-paths",), ["tests"])
    models = {}
    for md in model_dirs:
        base = os.path.join(pdir, md)
        for ext in ("sql", "py"):
            for p in glob.glob(os.path.join(base, "**", f"*.{ext}"), recursive=True):
                models[os.path.splitext(os.path.basename(p))[0]] = {"tests": set(), "key": False}
    yml_files = [p for p in glob.glob(os.path.join(pdir, "**", "*.yml"), recursive=True) +
                 glob.glob(os.path.join(pdir, "**", "*.yaml"), recursive=True)
                 if not any(seg in ("dbt_packages", "dbt_modules", "target", "integration_tests", "site-packages")
                            for seg in os.path.relpath(p, pdir).split(os.sep))]
    yml_errors = 0
    sources = source_tables = sources_fresh = 0
    unit_test_models = set()
    for p in yml_files:
        if os.path.samefile(p, os.path.join(repo_dir, project_path)):
            continue
        docs, ok = load_yaml(read(p))
        if not ok:
            yml_errors += 1
            continue
        for d in docs:
            if not isinstance(d, dict):
                continue
            for m in d.get("models") or []:
                if not isinstance(m, dict) or m.get("name") not in models:
                    continue
                rec = models[m["name"]]
                mt = tests_of(m)
                rec["tests"] |= set(mt)
                if set(mt) & KEY_SINGLE:
                    rec["key"] = True
                for col in m.get("columns") or []:
                    ct = set(tests_of(col))
                    rec["tests"] |= ct
                    if {"unique", "not_null"} <= ct or "primary_key" in ct:
                        rec["key"] = True
            for s in d.get("sources") or []:
                if not isinstance(s, dict):
                    continue
                sources += 1
                fresh = has_freshness(s)
                for t in s.get("tables") or []:
                    if isinstance(t, dict):
                        source_tables += 1
                        fresh = fresh or has_freshness(t)
                sources_fresh += fresh
            for u in d.get("unit_tests") or []:
                if isinstance(u, dict) and u.get("model") in models:
                    unit_test_models.add(u["model"])
    singular = 0
    for td in test_dirs:
        for p in glob.glob(os.path.join(pdir, td, "**", "*.sql"), recursive=True):
            text = read(p)
            if GENERIC_DEF.search(text):
                continue
            singular += 1
            for a, b in REF.findall(text):
                name = b or a
                if name in models:
                    models[name]["tests"].add("singular")
    for name in unit_test_models:
        models[name]["tests"].add("unit")
    n = len(models)
    tested = sum(1 for r in models.values() if r["tests"])
    keyed = sum(1 for r in models.values() if r["key"])
    out = {"models": n, "tested": tested, "key_tested": keyed,
           "tested_share": tested / n if n else None, "key_share": keyed / n if n else None,
           "models_with_unit_tests": len(unit_test_models), "singular_test_files": singular,
           "sources": sources, "source_tables": source_tables, "sources_with_freshness": sources_fresh,
           "freshness": sources_fresh > 0 or project_freshness(cfg),
           "yml_files": len(yml_files), "yml_parse_errors": yml_errors, "project_yml_parsed": cfg_ok}
    out.update(ci(repo_dir))
    return out


if __name__ == "__main__":
    print(json.dumps(measure(sys.argv[1], sys.argv[2]), indent=1))
