#!/usr/bin/env python3
"""vars-doctor: where does a host variable resolve from?

  vars-doctor -i inventory/lab.yml r29 ansible_user
  vars-doctor -i inventory/ -p playbooks/site.yml web1 http_port
  vars-doctor --cheatsheet

Three views of the same variable:
  1. inventory layer   `ansible-inventory --host HOST`   (what the inventory knows)
  2. task layer        `ansible HOST -m debug -a var=VAR` (what a task actually sees)
  3. source scan       every file under inventory/ and playbook dir that defines VAR
                       (inventory host/group entries, group_vars/, host_vars/)
If 1 and 2 disagree you have a discovery/precedence problem, not a typo.
Source scan is a heuristic that reads YAML/INI/JSON; it cannot see role defaults,
play vars, set_fact or -e, but it tells you when the value is NOT from a file.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys

import yaml

CHEATSHEET = """\
ANSIBLE VARIABLE PRECEDENCE (lowest -> highest; later wins)
   1  command line values (-u user)            [not -e]
   2  role defaults  (roles/x/defaults/main.yml)
   3  inventory file or script group vars
   4  inventory group_vars/all
   5  playbook group_vars/all
   6  inventory group_vars/*
   7  playbook group_vars/*
   8  inventory file or script host vars
   9  inventory host_vars/*
  10  playbook host_vars/*
  11  host facts / cached set_facts
  12  play vars
  13  play vars_prompt
  14  play vars_files
  15  role vars (roles/x/vars/main.yml)
  16  block vars
  17  task vars
  18  include_vars
  19  set_facts / registered vars
  20  role (and include_role) params
  21  include params
  22  extra vars (-e)   ALWAYS WINS

RULES OF THUMB
 * Same level, several groups: child group beats parent; equal depth -> alphabetical
   (last wins) unless ansible_group_priority is set (higher wins).
 * group_vars/ is loaded from TWO places: next to the inventory source and next to
   the playbook. NOT next to ansible.cfg, NOT next to your shell cwd.
 * Pin `inventory = ./inventory/...` in ansible.cfg so discovery is the same everywhere.
 * Connection vars (ansible_user, ansible_password, ansible_network_os) are read when the
   connection is made. With network_cli the persistent connection starts early, so
   anything set late (include_vars, set_fact) can arrive too late. Put them in
   inventory / group_vars, verify with this tool.
 * Dicts replace, they do not merge, unless hash_behaviour=merge (discouraged).
 * Debug a surprise:  vars-doctor -i INV HOST VAR   then  ansible-playbook -vvv
"""

INV_EXT = (".yml", ".yaml", ".json", "")


def run(cmd: list[str]) -> tuple[int, str, str]:
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, check=False)
    except FileNotFoundError:
        sys.exit(f"vars-doctor: '{cmd[0]}' not found on PATH (pip install ansible-core, or activate your venv)")
    return p.returncode, p.stdout, p.stderr


def inventory_view(inv: str | None, host: str) -> tuple[dict | None, str]:
    cmd = ["ansible-inventory", "--host", host]
    if inv:
        cmd[1:1] = ["-i", inv]
    rc, out, err = run(cmd)
    if rc != 0:
        return None, (err or out).strip()
    try:
        return json.loads(out), ""
    except json.JSONDecodeError:
        return None, "could not parse ansible-inventory output: " + out[:200]


UNDEF_MARKERS = ("VARIABLE IS NOT DEFINED", "is undefined")


def _is_defined(val: object) -> bool:
    return not (isinstance(val, str) and any(m in val for m in UNDEF_MARKERS))


def task_view(inv: str | None, playbook: str | None, host: str, var: str,
              extra: list[str]) -> tuple[object, bool, list[str], str]:
    """Ask Ansible what a task sees. Returns (value, defined, group_names, error).

    Without --playbook: ad-hoc `ansible -m debug` (group_vars next to inventory + cwd).
    With --playbook: a throw-away playbook is written NEXT TO that playbook so
    playbook-adjacent group_vars/host_vars are loaded exactly as in a real run.
    """
    inv_args = ["-i", inv] if inv else []
    if not playbook:
        out_vals = []
        for v in (var, "group_names"):
            rc, out, err = run(["ansible", *inv_args, host, "-m", "ansible.builtin.debug",
                                "-a", f"var={v}", "-c", "local", *extra])
            if rc != 0:
                return None, False, [], (out + err).strip()[-400:]
            try:
                out_vals.append(json.loads(out[out.index("=>") + 2:]).get(v))
            except ValueError:
                return None, False, [], out.strip()[-300:]
        val, groups = out_vals
        return val, _is_defined(val), list(groups or []), ""

    import tempfile
    pb_dir = os.path.dirname(os.path.abspath(playbook))
    play = (f"- hosts: {host}\n  gather_facts: false\n  connection: local\n  tasks:\n"
            f"    - ansible.builtin.debug:\n        msg: 'VDVAR::{{{{ {var} | default(\"__VD_UNDEF__\") | to_json }}}}'\n"
            f"    - ansible.builtin.debug:\n        msg: 'VDGRP::{{{{ group_names | to_json }}}}'\n")
    fd, tmp = tempfile.mkstemp(prefix=".vars-doctor-", suffix=".yml", dir=pb_dir)
    try:
        with os.fdopen(fd, "w") as fh:
            fh.write(play)
        rc, p_out, p_err = run(["ansible-playbook", *inv_args, tmp, *extra])
        p = type("P", (), {"stdout": p_out, "stderr": p_err})
        got = {}
        for m in re.finditer(r'"msg": ("VD(?:VAR|GRP)::.*")\s*$', p.stdout, re.M):
            s = json.loads(m.group(1))
            key, _, payload = s.partition("::")
            got[key] = json.loads(payload)
        if "VDVAR" not in got:
            return None, False, [], (p.stdout + p.stderr).strip()[-400:]
        val = got["VDVAR"]
        return (None if val == "__VD_UNDEF__" else val), val != "__VD_UNDEF__", list(got.get("VDGRP") or []), ""
    finally:
        os.unlink(tmp)


def load_any(path: str):
    try:
        with open(path, encoding="utf-8") as fh:
            return yaml.safe_load(fh)  # JSON is valid YAML
    except Exception:
        return None


def walk_vars_dir(root: str):
    """Yield files of a group_vars/host_vars tree (file or dir form)."""
    if os.path.isfile(root):
        yield root
    for dp, _dn, fn in os.walk(root):
        for f in sorted(fn):
            if f.endswith((".yml", ".yaml", ".json")):
                yield os.path.join(dp, f)


def scan_sources(inv: str | None, playbook: str | None, host: str, groups: list[str], var: str):
    """Return list of (rank, description, path, value) for definitions of var that apply to host."""
    roots: list[tuple[str, str]] = []  # (kind, dir)
    inv_dirs = []
    if inv:
        for item in inv.split(","):
            item = item.strip()
            if os.path.isdir(item):
                inv_dirs.append(item)
            elif os.path.isfile(item):
                inv_dirs.append(os.path.dirname(os.path.abspath(item)))
    pb_dir = os.path.dirname(os.path.abspath(playbook)) if playbook else None
    found = []

    # inventory file bodies (YAML/JSON): vars under all/groups/hosts
    files = []
    for item in (inv or "").split(","):
        item = item.strip()
        if os.path.isfile(item):
            files.append(item)
        elif os.path.isdir(item):
            files += [os.path.join(item, f) for f in sorted(os.listdir(item))
                      if os.path.isfile(os.path.join(item, f)) and f.endswith((".yml", ".yaml", ".json"))]
    for f in files:
        data = load_any(f)
        if isinstance(data, dict):
            found += _inv_body(data, f, host, groups, var, "all", 3)

    for kind, base_rank_all, base_rank_grp, base_rank_host, dirs in (
        ("inventory", 4, 6, 9, inv_dirs),
        ("playbook", 5, 7, 10, [pb_dir] if pb_dir else []),
    ):
        for d in dirs:
            for sub, who, rank in [("group_vars", "all", base_rank_all)] + \
                    [("group_vars", g, base_rank_grp) for g in groups if g != "all"] + \
                    [("host_vars", host, base_rank_host)]:
                for cand in (os.path.join(d, sub, who), *(os.path.join(d, sub, who + e) for e in (".yml", ".yaml", ".json"))):
                    if os.path.exists(cand):
                        for path in walk_vars_dir(cand):
                            data = load_any(path)
                            if isinstance(data, dict) and var in data:
                                found.append((rank, f"{kind} {sub}/{who}", path, data[var]))
    return sorted(found, key=lambda x: x[0])


def _inv_body(node: dict, path: str, host: str, groups: list[str], var: str, name: str, rank_grp: int):
    out = []
    for gname, g in (node.items() if "all" in node or "hosts" not in node else []):
        if not isinstance(g, dict):
            continue
        out += _group_body(g, path, host, groups, var, gname)
    if "hosts" in node and isinstance(node["hosts"], dict):
        out += _group_body(node, path, host, groups, var, name)
    return out


def _group_body(g: dict, path: str, host: str, groups: list[str], var: str, gname: str):
    out = []
    if gname == "all" or gname in groups:
        vs = g.get("vars")
        if isinstance(vs, dict) and var in vs:
            out.append((3, f"inventory file group vars [{gname}]", path, vs[var]))
    hosts = g.get("hosts")
    if isinstance(hosts, dict) and host in hosts and isinstance(hosts[host], dict) and var in hosts[host]:
        out.append((8, f"inventory file host vars [{gname}/{host}]", path, hosts[host][var]))
    for cname, child in (g.get("children") or {}).items():
        if isinstance(child, dict):
            out += _group_body(child, path, host, groups, var, cname)
    return out


def main() -> int:
    ap = argparse.ArgumentParser(description="Show where a host variable resolves from.")
    ap.add_argument("-i", "--inventory", help="inventory path(s), comma separated (default: ansible.cfg)")
    ap.add_argument("-p", "--playbook", help="playbook path (to scan its group_vars/host_vars)")
    ap.add_argument("-e", "--extra-vars", action="append", default=[], help="passed to ansible (shown as winner if it sets VAR)")
    ap.add_argument("--cheatsheet", action="store_true", help="print the precedence cheat sheet and exit")
    ap.add_argument("host", nargs="?")
    ap.add_argument("var", nargs="?")
    a = ap.parse_args()
    if a.cheatsheet:
        print(CHEATSHEET)
        return 0
    if not (a.host and a.var):
        ap.error("host and var are required (or use --cheatsheet)")

    inv_vars, err = inventory_view(a.inventory, a.host)
    if inv_vars is None:
        print(f"ansible-inventory failed: {err}", file=sys.stderr)
        return 2
    extra: list[str] = []
    for e in a.extra_vars:
        extra += ["-e", e]
    val, defined, groups, terr = task_view(a.inventory, a.playbook, a.host, a.var, extra)
    if terr:
        print(f"ansible debug failed: {terr}", file=sys.stderr)
        return 2

    print(f"host: {a.host}   var: {a.var}   groups: {', '.join(groups) or '-'}")
    print(f"  inventory layer : {json.dumps(inv_vars[a.var]) if a.var in inv_vars else '(not set)'}")
    print(f"  task layer      : {json.dumps(val) if defined else '(undefined)'}")
    status = 0
    in_inv = a.var in inv_vars
    if in_inv and defined and inv_vars[a.var] != val:
        print("  !! layers DISAGREE: something outside the inventory layer wins (playbook group_vars, play/role vars, -e, include_vars...)")
        status = 1
    if not in_inv and defined:
        print("  !! task layer has a value the inventory does not: it comes from play/role/facts/-e, not inventory")
    if in_inv and not defined:
        print("  !! inventory has it but the task does not see it: discovery problem")
        status = 1
    if not in_inv and not defined:
        print("  !! not defined anywhere Ansible looked")
        status = 1

    hits = scan_sources(a.inventory, a.playbook, a.host, groups, a.var)
    print("  definitions found on disk (low -> high precedence):")
    if not hits:
        print("    (none: value, if any, is not in inventory/group_vars/host_vars files)")
    for rank, desc, path, v in hits:
        mark = "  <== matches effective value" if defined and v == val else ""
        print(f"    #{rank:<2} {desc:<42} {path} = {json.dumps(v)}{mark}")
    if extra and any(a.var in e for e in a.extra_vars):
        print("  note: -e given for this var: extra vars always win")
    print("  (run with --cheatsheet for the precedence table)")
    return status


if __name__ == "__main__":
    sys.exit(main())
