# Databricks notebook source
# Test Sweep Batch 2: insurance-optimise, insurance-deploy, insurance-distill
# Installs each package from GitHub (main branch) in an isolated venv, runs pytest

# COMMAND ----------

import subprocess, sys, os, json, shutil
from pathlib import Path

results = {}

REPOS = [
    ("insurance-optimise", "https://github.com/burning-cost/insurance-optimise"),
    ("insurance-deploy",   "https://github.com/burning-cost/insurance-deploy"),
    ("insurance-distill",  "https://github.com/burning-cost/insurance-distill"),
]

# COMMAND ----------

for (name, github_url) in REPOS:
    print(f"\n{'='*60}")
    print(f"REPO: {name}")
    print(f"{'='*60}")

    work_dir = f"/tmp/work-{name}"
    venv_dir = f"/tmp/venv-{name}"

    # Clean up any leftover dirs
    shutil.rmtree(work_dir, ignore_errors=True)
    shutil.rmtree(venv_dir, ignore_errors=True)

    # Clone the repo
    print(f"Cloning {github_url}...")
    clone_r = subprocess.run(
        ["git", "clone", "--depth=1", github_url, work_dir],
        capture_output=True, text=True, timeout=120
    )
    if clone_r.returncode != 0:
        print(f"CLONE FAILED: {clone_r.stderr}")
        results[name] = {"install": False, "error": f"clone failed: {clone_r.stderr[:300]}"}
        continue
    print("Clone OK")

    # Create venv
    venv_r = subprocess.run(
        [sys.executable, "-m", "venv", venv_dir],
        capture_output=True, text=True, timeout=60
    )
    if venv_r.returncode != 0:
        print(f"VENV FAILED: {venv_r.stderr}")
        results[name] = {"install": False, "error": f"venv failed: {venv_r.stderr[:300]}"}
        shutil.rmtree(work_dir, ignore_errors=True)
        continue

    pip = f"{venv_dir}/bin/pip"
    python = f"{venv_dir}/bin/python"

    # Upgrade pip silently
    subprocess.run([pip, "install", "--upgrade", "pip", "-q"], capture_output=True)

    # Install package with dev extras
    print(f"Installing {name}[dev]...")
    install_r = subprocess.run(
        [pip, "install", "-e", f"{work_dir}[dev]", "-q"],
        capture_output=True, text=True, timeout=300,
        cwd=work_dir
    )
    install_out = (install_r.stdout + install_r.stderr).strip()
    install_tail = "\n".join(install_out.split("\n")[-8:])
    print(f"Install tail:\n{install_tail}")

    if install_r.returncode != 0:
        print(f"INSTALL FAILED (rc={install_r.returncode})")
        results[name] = {"install": False, "error": install_tail}
        shutil.rmtree(work_dir, ignore_errors=True)
        shutil.rmtree(venv_dir, ignore_errors=True)
        continue

    print("Install OK")

    # Run pytest
    print(f"Running pytest...")
    pytest_r = subprocess.run(
        [python, "-m", "pytest", "--tb=short", "-v", "tests/"],
        capture_output=True, text=True, timeout=360,
        cwd=work_dir
    )
    output = pytest_r.stdout + pytest_r.stderr
    all_lines = output.strip().split("\n")
    tail = "\n".join(all_lines[-50:])
    print(f"--- pytest output (last 50 lines) ---\n{tail}")

    # Parse summary
    summary_line = ""
    for line in reversed(all_lines):
        if "passed" in line or "failed" in line or "error" in line:
            summary_line = line.strip()
            break

    results[name] = {
        "install": True,
        "returncode": pytest_r.returncode,
        "summary": summary_line,
        "output_tail": tail,
    }

    shutil.rmtree(work_dir, ignore_errors=True)
    shutil.rmtree(venv_dir, ignore_errors=True)

# COMMAND ----------

print("\n\n" + "="*70)
print("FINAL SUMMARY")
print("="*70)
for name, res in results.items():
    print(f"\n[{name}]")
    if not res.get("install"):
        print(f"  Install: FAILED")
        print(f"  Error:   {res.get('error','')[:300]}")
    else:
        rc = res.get("returncode", -1)
        status = "ALL PASSED" if rc == 0 else "FAILURES/ERRORS"
        print(f"  Install:  OK")
        print(f"  Pytest:   {status} (rc={rc})")
        print(f"  Summary:  {res.get('summary','(no summary line found)')}")

# COMMAND ----------

import json
dbutils.notebook.exit(json.dumps({k: {
    "install": v.get("install"),
    "returncode": v.get("returncode"),
    "summary": v.get("summary",""),
    "output_tail": v.get("output_tail",""),
    "error": v.get("error",""),
} for k, v in results.items()}))
