import urllib.request
import json
import urllib.parse

def test_search_bangumi():
    keyword = "No game no life"
    url = f"https://api.bgm.tv/search/subject/{urllib.parse.quote(keyword)}?type=2"
    headers = {
        'User-Agent': 'thinktraveller/anitabi-mcpserver (https://github.com/thinktraveller/Anitabi_MCPserver)'
    }
    req = urllib.request.Request(url, headers=headers)
    try:
        with urllib.request.urlopen(req) as response:
            data = json.loads(response.read().decode('utf-8'))
            print("=== Search Bangumi ===")
            print(json.dumps(data, indent=2, ensure_ascii=False)[:500] + "...")
            if 'list' in data and len(data['list']) > 0:
                return data['list'][0]['id']
            return None
    except Exception as e:
        print(f"Error searching bangumi: {e}")
        return None

def test_anitabi_lite(subject_id):
    url = f"https://api.anitabi.cn/bangumi/{subject_id}/lite"
    headers = {
        'User-Agent': 'thinktraveller/anitabi-mcpserver (https://github.com/thinktraveller/Anitabi_MCPserver)'
    }
    req = urllib.request.Request(url, headers=headers)
    try:
        with urllib.request.urlopen(req) as response:
            data = json.loads(response.read().decode('utf-8'))
            print("\n=== Anitabi Lite Info ===")
            print(json.dumps(data, indent=2, ensure_ascii=False)[:500] + "...")
    except Exception as e:
        print(f"Error fetching lite info for {subject_id}: {e}")

def test_anitabi_detail(subject_id):
    url = f"https://api.anitabi.cn/bangumi/{subject_id}/points/detail?haveImage=true"
    headers = {
        'User-Agent': 'thinktraveller/anitabi-mcpserver (https://github.com/thinktraveller/Anitabi_MCPserver)'
    }
    req = urllib.request.Request(url, headers=headers)
    try:
        with urllib.request.urlopen(req) as response:
            data = json.loads(response.read().decode('utf-8'))
            print("\n=== Anitabi Detail Info ===")
            print(json.dumps(data, indent=2, ensure_ascii=False)[:500] + "...")
    except Exception as e:
        print(f"Error fetching detail info for {subject_id}: {e}")

if __name__ == "__main__":
    bangumi_id = test_search_bangumi()
    if bangumi_id:
        print(f"\nFound Bangumi ID: {bangumi_id}")
    
    # test with known good ID
    known_id = 115908
    print(f"\nTesting with known Bangumi ID: {known_id}")
    test_anitabi_lite(known_id)
    test_anitabi_detail(known_id)
