"""Read dbt project metadata without executing any repository content."""
import json
import os
from pathlib import Path
import re
import shlex
import sys

import yaml


IGNORED = {"dbt_packages", "dbt_modules", "target", "integration_tests"}
JINJA = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.S)


def read(path):
    try:
        return path.read_text(encoding="utf-8-sig")
    except (OSError, UnicodeError):
        return ""


def document(path):
    text = read(path)
    for candidate in (text, JINJA.sub("JINJA", text)):
        try:
            value = yaml.safe_load(candidate)
            if isinstance(value, dict):
                return value
        except yaml.YAMLError:
            pass
    return {}


def records(value):
    return [item for item in value if isinstance(item, dict)] if isinstance(value, list) else []


def inside(path, root):
    try:
        relative = path.resolve().relative_to(root)
        return not any(part in IGNORED for part in relative.parts)
    except (ValueError, OSError, RuntimeError):
        return False


def files(root, folder):
    # Only project-contained paths count; symlinks must not escape the project.
    folder = root / folder
    if not inside(folder, root) or not folder.is_dir():
        return
    for current, dirs, names in os.walk(folder, followlinks=False):
        dirs[:] = [d for d in dirs if d not in IGNORED and not (Path(current) / d).is_symlink()]
        for name in names:
            path = Path(current) / name
            if inside(path, root):
                yield path


def folders(config, key, default, legacy=None):
    value = config.get(key, config.get(legacy, default) if legacy else default)
    # Accept a scalar folder as a convenience; explicit empty lists stay empty.
    if isinstance(value, str):
        return [value]
    return [x for x in value if isinstance(x, str)] if isinstance(value, list) else default


def test_names(entry):
    result = set()
    for key in ("tests", "data_tests"):
        value = entry.get(key, [])
        if not isinstance(value, list):
            continue
        for test in value:
            names = [test] if isinstance(test, str) else test.keys() if isinstance(test, dict) else []
            result.update(name.rsplit(".", 1)[-1] for name in names if isinstance(name, str))
    return result


def has_freshness(value):
    # dbt_project.yml allows nested package/source/table configuration mappings.
    if isinstance(value, dict):
        return any(
            (key in ("freshness", "+freshness") and item is not None)
            or has_freshness(item) for key, item in value.items()
        )
    if isinstance(value, list):
        return any(has_freshness(item) for item in value)
    return False


def source_freshness(doc, project=False):
    sources = doc.get("sources")
    if project:
        return has_freshness(sources)
    for source in records(sources):
        for entry in [source] + records(source.get("tables")):
            # Modern dbt also accepts freshness inside config.
            if entry.get("freshness") is not None:
                return True
            config = entry.get("config", {})
            if isinstance(config, dict) and config.get("freshness") is not None:
                return True
    return False


def sql_without_comments(text):
    # Preserve quoted strings, including ref arguments, while removing SQL comments.
    pattern = r"('(?:''|[^'])*'|\"(?:\"\"|[^\"])*\")|--[^\n]*|/\*.*?\*/|\{#.*?#\}"
    return re.sub(pattern, lambda m: m.group(1) or " ", text, flags=re.S)


def refs(text):
    text = sql_without_comments(text)
    if re.search(r"\{%[-+]?\s*test\s+", text):
        return set()
    # Two-argument refs attach to the final (model) argument; versions are allowed.
    pattern = r"\bref\s*\(\s*(['\"])([^'\"]+)\1\s*(?:,\s*(['\"])([^'\"]+)\3\s*)?(?=[,)])"
    return {m.group(4) or m.group(2) for m in re.finditer(pattern, text)}


def runs_tests(script):
    # Inspect shell command positions; quoted echo text and comments are not runs.
    script = script.replace("\\\n", " ")
    try:
        lexer = shlex.shlex(script, posix=True, punctuation_chars=";&|()\n")
        lexer.whitespace = " \t\r"
        tokens = list(lexer)
    except ValueError:
        return False
    start = True
    index = 0
    while index < len(tokens):
        token = tokens[index]
        if token and all(c in ";&|()\n" for c in token):
            start = True
        elif start:
            if token in ("then", "do", "env", "command", "exec") or re.match(r"^[A-Za-z_][A-Za-z_0-9]*=", token):
                index += 1
                continue
            if token == "dbt" or token.endswith("/dbt"):
                tail = tokens[index + 1:]
                for arg in tail:
                    if arg and all(c in ";&|()\n" for c in arg):
                        break
                    if arg in ("test", "build"):
                        return True
                    if arg in {"run", "compile", "seed", "snapshot", "deps", "debug", "parse", "ls", "list", "source", "docs", "clean", "run-operation", "retry", "show"}:
                        break
            start = False
        index += 1
    return False


def ci_tests(repo):
    workflows = repo / ".github" / "workflows"
    if not workflows.is_dir():
        return False
    for path in workflows.iterdir():
        if path.suffix.lower() not in (".yml", ".yaml") or not path.is_file():
            continue
        if not path.resolve().is_relative_to(repo):
            continue
        doc = document(path)
        # PyYAML's YAML 1.1 resolver interprets the unquoted key `on` as True.
        triggers = doc.get("on", doc.get(True, []))
        triggers = [triggers] if isinstance(triggers, str) else triggers
        if not isinstance(triggers, (list, dict)):
            continue
        if not any(t in triggers for t in ("pull_request", "pull_request_target", "merge_group")):
            continue
        jobs = doc.get("jobs", {})
        if not isinstance(jobs, dict):
            continue
        for job in jobs.values():
            if not isinstance(job, dict):
                continue
            for step in records(job.get("steps")):
                if isinstance(step.get("run"), str) and runs_tests(step["run"]):
                    return True
    return False


def count(repo, project_file):
    repo = repo.resolve()
    project = (repo / project_file).resolve()
    if not project.is_relative_to(repo):
        raise ValueError("project_file must be inside repo_dir")
    root = project.parent
    config = document(project)
    model_files = set()
    for folder in folders(config, "model-paths", ["models"], "source-paths"):
        model_files.update(p.resolve() for p in files(root, folder) if p.suffix.lower() in (".sql", ".py"))
    names = {p.stem for p in model_files}
    tested, key_tested = set(), set()
    columns = {}
    freshness = source_freshness(config, project=True)
    for path in files(root, "."):
        if path == project or path.suffix.lower() not in (".yml", ".yaml"):
            continue
        doc = document(path)
        freshness |= source_freshness(doc)
        for entry in records(doc.get("models")):
            name = entry.get("name")
            if not isinstance(name, str) or name not in names:
                continue
            tests = test_names(entry)
            if tests:
                tested.add(name)
            if tests & {"primary_key", "unique_combination_of_columns"}:
                key_tested.add(name)
            for column in records(entry.get("columns")):
                tests = test_names(column)
                if tests:
                    tested.add(name)
                column_name = column.get("name")
                if not isinstance(column_name, str):
                    continue
                # Merge split declarations of the same model column across files.
                accumulated = columns.setdefault((name, column_name), set())
                accumulated.update(tests)
                if "primary_key" in accumulated or {"unique", "not_null"} <= accumulated:
                    key_tested.add(name)
        for entry in records(doc.get("unit_tests")):
            if isinstance(entry.get("model"), str) and entry["model"] in names:
                tested.add(entry["model"])
    for folder in folders(config, "test-paths", ["tests"]):
        for path in files(root, folder):
            if path.suffix.lower() == ".sql":
                tested.update(refs(read(path)) & names)
    # Models are files; duplicate stems share name-matched metadata but each counts.
    return {"models": len(model_files), "tested": sum(p.stem in tested for p in model_files),
            "key_tested": sum(p.stem in key_tested for p in model_files),
            "freshness": bool(freshness), "ci_tests_before_merge": ci_tests(repo)}


if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise SystemExit("usage: python3 independent_count.py <repo_dir> <project_file>")
    print(json.dumps(count(Path(sys.argv[1]), sys.argv[2])))
