#!/usr/bin/env python3
"""Test all 4 ARIS tiers — access matrix verification."""
import asyncio
import json
import os
import sys

async def test_tiers():
    from aris_mcp.server import (
        aris_dev_license, aris_activate, aris_list_skills, aris_get_skill,
        aris_route_task, aris_guardian, aris_memory_save, aris_budget_set,
        aris_forge, aris_scout_report, aris_analytics, _sessions
    )

    tiers = ["free", "pro", "shield", "intel"]
    results = []
    sep = "=" * 60

    for tier in tiers:
        _sessions.clear()

        print(f"\n{sep}")
        print(f"TIER: {tier.upper()}")
        print(sep)

        if tier != "free":
            lic = json.loads(await aris_dev_license(tier=tier, days=30))
            if lic["status"] != "ok":
                print(f"  LICENSE FAIL: {lic}")
                results.append((tier, False))
                continue
            act = json.loads(await aris_activate(lic["license_key"]))
            print(f"  Activation: {act['status']} tier={act.get('tier','')} addons={act.get('addons',[])}")
        else:
            print(f"  No license (free tier)")

        # Skills count
        sk = json.loads(await aris_list_skills("all"))
        print(f"  Skills: {sk['accessible']}/{sk['total']} accessible")

        # Test skill access per tier
        free_r = json.loads(await aris_get_skill("code-reviewer"))
        free_ok = free_r.get("status") == "ok"

        pro_r = json.loads(await aris_get_skill("architect-review"))
        pro_ok = pro_r.get("status") == "ok"

        shield_r = json.loads(await aris_get_skill("vulnerability-scanner"))
        shield_ok = shield_r.get("status") == "ok"

        intel_r = json.loads(await aris_get_skill("predictive-analytics"))
        intel_ok = intel_r.get("status") == "ok"

        # Test gated tools
        route_r = json.loads(await aris_route_task("test task", "claude"))
        route_ok = route_r["status"] == "ok"

        guard_r = json.loads(await aris_guardian(""))
        guard_ok = guard_r["status"] == "ok"

        scout_r = json.loads(await aris_scout_report())
        scout_ok = scout_r["status"] == "ok"

        analy_r = json.loads(await aris_analytics("7d"))
        analy_ok = analy_r["status"] == "ok"

        budget_r = json.loads(await aris_budget_set(monthly_limit=50))
        budget_ok = budget_r["status"] == "ok"

        forge_r = json.loads(await aris_forge("tier-test", "test", "test content", "dev", "free", ""))
        forge_ok = forge_r.get("status") == "created"

        # Memory is ungated
        mem_r = json.loads(await aris_memory_save("tier-test", "value", "fact", ""))
        mem_ok = mem_r["status"] == "saved"

        print(f"  free skill:   {'OK' if free_ok else 'LOCKED'}")
        print(f"  pro skill:    {'OK' if pro_ok else 'LOCKED'}")
        print(f"  shield skill: {'OK' if shield_ok else 'LOCKED'}")
        print(f"  intel skill:  {'OK' if intel_ok else 'LOCKED'}")
        print(f"  router:       {'OK' if route_ok else 'LOCKED'}")
        print(f"  guardian:     {'OK' if guard_ok else 'LOCKED'}")
        print(f"  scout:        {'OK' if scout_ok else 'LOCKED'}")
        print(f"  analytics:    {'OK' if analy_ok else 'LOCKED'}")
        print(f"  budget:       {'OK' if budget_ok else 'LOCKED'}")
        print(f"  forge:        {'OK' if forge_ok else 'LOCKED'}")
        print(f"  memory:       {'OK' if mem_ok else 'FAIL'}")

        # Expected access matrix
        # free: only free skills + memory
        # pro: free + pro skills + all tools
        # shield: free + pro + shield skills + all tools
        # intel: free + pro + intel skills + all tools (NOT shield unless addon)
        expected = {
            "free":   {"free_sk": True,  "pro_sk": False, "shield_sk": False, "intel_sk": False,
                       "router": False, "guardian": False, "scout": False, "analytics": False,
                       "budget": False, "forge": False, "memory": True},
            "pro":    {"free_sk": True,  "pro_sk": True,  "shield_sk": False, "intel_sk": False,
                       "router": True,  "guardian": True,  "scout": True,  "analytics": True,
                       "budget": True,  "forge": True,  "memory": True},
            "shield": {"free_sk": True,  "pro_sk": True,  "shield_sk": True,  "intel_sk": False,
                       "router": True,  "guardian": True,  "scout": True,  "analytics": True,
                       "budget": True,  "forge": True,  "memory": True},
            "intel":  {"free_sk": True,  "pro_sk": True,  "shield_sk": False, "intel_sk": True,
                       "router": True,  "guardian": True,  "scout": True,  "analytics": True,
                       "budget": True,  "forge": True,  "memory": True},
        }

        actual = {
            "free_sk": free_ok, "pro_sk": pro_ok, "shield_sk": shield_ok, "intel_sk": intel_ok,
            "router": route_ok, "guardian": guard_ok, "scout": scout_ok, "analytics": analy_ok,
            "budget": budget_ok, "forge": forge_ok, "memory": mem_ok,
        }

        print(f"\n  ACCESS MATRIX VERIFICATION:")
        tier_pass = True
        for key in sorted(expected[tier].keys()):
            exp = expected[tier][key]
            act = actual[key]
            match = exp == act
            if not match:
                tier_pass = False
            status = "PASS" if match else "FAIL"
            print(f"    {key:12s}: expected={str(exp):5s} actual={str(act):5s} [{status}]")

        results.append((tier, tier_pass))

    # Cleanup
    for name in ["tier-test"]:
        path = os.path.join(os.path.dirname(__file__), "..", "..", "server-skills", "free", f"{name}.md")
        if os.path.exists(path):
            os.remove(path)

    print(f"\n{sep}")
    print("TIER VERIFICATION SUMMARY")
    print(sep)
    for tier, ok in results:
        print(f"  {tier.upper():8s}: {'PASS' if ok else 'FAIL'}")

    all_pass = all(ok for _, ok in results)
    print(f"\n{'ALL 4 TIERS CORRECT' if all_pass else 'TIER ISSUES FOUND'}")
    return all_pass

if __name__ == "__main__":
    ok = asyncio.run(test_tiers())
    sys.exit(0 if ok else 1)
