#!/usr/bin/env python3
"""
Usage: python tk_experiments.py <wiki>
Example: python tk_experiments.py enwiki
"""

import sys
import json
import urllib.request
from datetime import datetime, timezone

API_URL = "https://test-kitchen.wikimedia.org/api/v1/experiments"


def fetch_experiments():
    req = urllib.request.Request(
        API_URL,
        headers={"User-Agent": "tk-experiments-script/1.0 (python)"},
    )
    with urllib.request.urlopen(req) as response:
        return json.loads(response.read())


def is_running(exp):
    now = datetime.now(timezone.utc)
    start = datetime.fromisoformat(exp["start"].replace("Z", "+00:00"))
    end = datetime.fromisoformat(exp["end"].replace("Z", "+00:00"))
    return start <= now <= end


def wiki_in_experiment(wiki, exp):
    for rate, wikis in exp["sample_rate"].items():
        if isinstance(wikis, list) and wiki in wikis:
            return float(rate)
    return None


def main():
    if len(sys.argv) < 2:
        print("Usage: python tk_experiments.py <wiki>")
        print("Example: python tk_experiments.py enwiki")
        sys.exit(1)

    wiki = sys.argv[1]

    print(f"Fetching experiments from {API_URL}...")
    experiments = fetch_experiments()

    running = [e for e in experiments if is_running(e)]
    matches = [(e, wiki_in_experiment(wiki, e)) for e in running]
    matches = [(e, rate) for e, rate in matches if rate is not None]

    print(f"\nExperiments currently running on {wiki}: {len(matches)}\n")

    if not matches:
        print("None found.")
        return

    for exp, rate in matches:
        end_dt = datetime.fromisoformat(exp["end"].replace("Z", "+00:00"))
        days_left = (end_dt - datetime.now(timezone.utc)).days
        print(f"  {exp['name']}")
        print(f"    Sample rate : {rate:.1%} ({exp['user_identifier_type']})")
        print(f"    Groups      : {', '.join(exp['groups'])}")
        print(f"    Ends        : {exp['end']} ({days_left}d remaining)")
        print(f"    Stream      : {exp['stream_name']}")
        print()


if __name__ == "__main__":
    main()
