#!/usr/bin/env python3
import csv
import pathlib
import sys

if len(sys.argv) < 4:
    print("ERROR:missing_args:usage: info.py <root> <sites_path> <config_path>")
    sys.exit(2)

root = pathlib.Path(sys.argv[1])
sites_path = pathlib.Path(sys.argv[2])
config_path = pathlib.Path(sys.argv[3])

print(f"Repo root: {root}")

if config_path.exists():
    temp_dir = None
    for line in config_path.read_text().splitlines():
        if line.strip().startswith("temp_dir"):
            temp_dir = line.split("=", 1)[1].strip().strip('"')
            break
    print(f"config.toml: present at {config_path}")
    if temp_dir:
        print(f"temp_dir: {temp_dir}")
    else:
        print("temp_dir: (not set)")
else:
    print(f"config.toml: MISSING (expected at {config_path})")

if sites_path.exists():
    rows = []
    with sites_path.open() as fh:
        reader = csv.reader(fh)
        for row in reader:
            if not row:
                continue
            domain = (row[0] or "").strip()
            theme = (row[1] if len(row) > 1 else "").strip()
            if not domain and not theme:
                continue
            rows.append((domain, theme))
            if len(rows) >= 5:
                break
    total = sum(1 for _ in sites_path.open())
    print(f"sites.csv: present at {sites_path} (rows: {total})")
    if rows:
        print("sample rows:")
        for domain, theme in rows:
            print(f"  - domain='{domain}' theme='{theme}'")
    else:
        print("sites.csv has no non-empty rows")
else:
    print(f"sites.csv: MISSING (place it at {sites_path})")

# Directory status (safe summary, no ls)
dirs = [
    ("tools", root / "tools"),
    (".smbatcher", root / ".smbatcher"),
    ("tools/check", root / "tools" / "check"),
    ("tools/prepare", root / "tools" / "prepare"),
]

missing_critical = []
for label, path in dirs:
    if path.exists():
        items = []
        if path.is_dir():
            try:
                for entry in sorted(path.iterdir()):
                    items.append(entry.name + ("/" if entry.is_dir() else ""))
                    if len(items) >= 5:
                        break
            except Exception:
                items = ["(unable to read entries)"]
            count = sum(1 for _ in path.iterdir()) if path.is_dir() else 1
            preview = ", ".join(items) if items else "(empty)"
            print(f"{label}: present at {path} (entries: {count}; sample: {preview})")
        else:
            print(f"{label}: present at {path} (not a directory)")
    else:
        print(f"{label}: MISSING (expected at {path})")
        missing_critical.append(label)

if missing_critical or not sites_path.exists():
    print(f"\nFAIL:missing_prerequisites:{','.join(missing_critical) if missing_critical else 'sites.csv'}")
    sys.exit(1)
else:
    print(f"\nOK:info_complete:all prerequisites present")
