#!/usr/bin/env python3
"""Template for using the snoHUB2 web services from Python.

It calls four services, parses the JSON they return, and prints a short summary.
It needs only Python 3 and no extra packages, login, or API key.

    python snohub2_api_example.py

To try other snoRNAs, edit SNORNA and SNORNA_SET below.
"""

import json
import sys
import urllib.error
import urllib.request

# pass another address as the first argument to use a different server
BASE_URL = sys.argv[1].rstrip("/") if len(sys.argv) > 1 else "https://snohub2.k8s.maayanlab.cloud"

SNORNA = "SNORD116-1"
SNORNA_SET = ["SNORD116-1", "SNORD116-2", "SNORD116-3", "SNORD116-4"]


def call_service(path, body=None):
    """GET a service, or POST to it when a JSON body is given, and return its data."""
    request = urllib.request.Request(
        f"{BASE_URL}{path}",
        data=None if body is None else json.dumps(body).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )

    try:
        with urllib.request.urlopen(request, timeout=120) as response:
            return json.load(response)["data"]
    except urllib.error.HTTPError as error:
        raise SystemExit(f"{path} failed: {json.load(error).get('error', error)}")


# 1. Every snoRNA symbol and Ensembl ID that can be queried
names = call_service("/api/snornas")
print(f"snoHUB2 recognizes {len(names):,} snoRNA names and IDs.")

# 2. Where one snoRNA is in the genome
location = call_service(f"/api/snorna/{SNORNA}/location")
print(f"\n{SNORNA}: {location['location']}, {location['length_label']}")

# 3. The full report for one snoRNA
report = call_service(f"/api/snorna/{SNORNA}")

print(f"\nTop correlated protein-coding genes for {SNORNA}:")
for gene in report["top_correlated_genes"][:5]:
    print(f"  {gene['gene']} (r = {gene['correlation']:.3f})")

print(f"\nHighest correlated gene-set terms for {SNORNA}:")
for term in report["overall_highest_terms"][:5]:
    print(f"  {term['term']} ({term['library']})")

# 4. Set analysis for several snoRNAs
result = call_service("/api/set-analysis", {"snornas": SNORNA_SET})

print(
    f"\nSet analysis of {len(result['snornas'])} snoRNAs: "
    f"{len(result['genes'])} related genes, "
    f"{result['significant_terms']} significant terms."
)
for library, terms in result["library_terms"].items():
    term = terms[0]
    print(f"  {library}: {term['term']} (adjusted p = {term['adjusted_p_value']:.2g})")
