#!/usr/bin/env python3
"""
[OPS] Cross-Repo Test Suite
Part of the Gemini Sovereign Infrastructure Suite.

Verifies the fleet works as a system by running tests across all core repositories.
"""

import os
import sys
import subprocess
import argparse
from pathlib import Path

# --- CONFIGURATION ---
REPOS = ["timmy-config", "hermes-agent", "the-nexus"]

class CrossRepoTester:
    def __init__(self, root_dir: str):
        self.root_dir = Path(root_dir).resolve()

    def log(self, message: str):
        print(f"[*] {message}")

    def run_tests(self):
        results = {}
        
        for repo in REPOS:
            repo_path = self.root_dir / repo
            if not repo_path.exists():
                # Try sibling directory if we are in one of the repos
                repo_path = self.root_dir.parent / repo
                
            if not repo_path.exists():
                print(f"[WARNING] Repo {repo} not found at {repo_path}")
                results[repo] = "MISSING"
                continue

            self.log(f"Running tests for {repo}...")
            
            # Determine test command
            test_cmd = ["pytest"]
            if repo == "hermes-agent":
                test_cmd = ["python3", "-m", "pytest", "tests"]
            elif repo == "the-nexus":
                test_cmd = ["pytest", "tests"]
            
            try:
                # Check if pytest is available
                subprocess.run(["pytest", "--version"], capture_output=True)
                
                res = subprocess.run(test_cmd, cwd=str(repo_path), capture_output=True, text=True)
                if res.returncode == 0:
                    results[repo] = "PASSED"
                else:
                    results[repo] = "FAILED"
                    # Print a snippet of the failure
                    print(f"  [!] {repo} failed tests. Stderr snippet:")
                    print("\n".join(res.stderr.split("\n")[-10:]))
            except FileNotFoundError:
                results[repo] = "ERROR: pytest not found"
            except Exception as e:
                results[repo] = f"ERROR: {e}"

        self.report(results)

    def report(self, results: dict):
        print("\n--- Cross-Repo Test Report ---")
        all_passed = True
        for repo, status in results.items():
            icon = "✅" if status == "PASSED" else "❌"
            print(f"{icon} {repo:<15} | {status}")
            if status != "PASSED":
                all_passed = False
                
        if all_passed:
            print("\n[SUCCESS] All systems operational. The fleet is sound.")
        else:
            print("\n[FAILURE] System instability detected.")

def main():
    parser = argparse.ArgumentParser(description="Gemini Cross-Repo Tester")
    parser.add_argument("--root", default=".", help="Root directory containing all repos")
    args = parser.parse_args()
    
    tester = CrossRepoTester(args.root)
    tester.run_tests()

if __name__ == "__main__":
    main()
