"""
Test script: Team Draft → Main full flow.
Run inside container: python /app/temp/test_team_flow.py
"""

import asyncio
import sys
sys.path.insert(0, "/app")

from common.mongo_client import init_mongodb
from common.team.services import team_service


async def main():
    await init_mongodb()
    
    user_a = "test_user_alice"
    user_b = "test_user_bob"
    
    # 1. Create team
    print("=" * 50)
    print("1. CREATE TEAM")
    team = await team_service.create_team("Test Team", "Testing draft → main", user_a)
    team_id = team["id"]
    print(f"   ✅ Team: {team['name']} (id={team_id})")
    print(f"   📎 Invite code: {team['invite_code']}")
    
    # 2. Bob joins
    print("\n2. BOB JOINS")
    joined = await team_service.join_team(team["invite_code"], user_b)
    print(f"   ✅ Bob joined: {joined['name']}")
    
    # 3. Create drafts
    print("\n3. CREATE DRAFTS")
    d1 = await team_service.create_draft(team_id, user_a, "Dùng Google Vision cho OCR", ["#idea"])
    d2 = await team_service.create_draft(team_id, user_b, "Tesseract free hơn, cân nhắc?", ["#idea", "#blocker"])
    d3 = await team_service.create_draft(team_id, user_a, "Budget: $50/tháng max", ["#plan"])
    print(f"   ✅ Draft 1: {d1['content'][:40]}... (by Alice)")
    print(f"   ✅ Draft 2: {d2['content'][:40]}... (by Bob)")
    print(f"   ✅ Draft 3: {d3['content'][:40]}... (by Alice)")
    
    # 4. List drafts
    print("\n4. LIST DRAFTS")
    drafts = await team_service.list_drafts(team_id, user_a)
    print(f"   📝 {len(drafts)} drafts in team")
    for d in drafts:
        print(f"      - [{d['space']}] {d['content'][:50]}")
    
    # 5. Merge draft 1 → main
    print("\n5. MERGE DRAFT → MAIN")
    merged = await team_service.merge_to_main(team_id, d1["id"], user_a)
    print(f"   ✅ Merged: {merged['content'][:40]}...")
    print(f"   📌 Space: {merged['space']}, merged_by: {merged['merged_by']}")
    
    # 6. List main
    print("\n6. LIST MAIN")
    main_items = await team_service.list_main(team_id, user_a)
    print(f"   ✅ {len(main_items)} items in main")
    for m in main_items:
        print(f"      - [{m['space']}] {m['content'][:50]}")
    
    # 7. List drafts (should be -1)
    print("\n7. DRAFTS AFTER MERGE")
    drafts_after = await team_service.list_drafts(team_id, user_a)
    print(f"   📝 {len(drafts_after)} drafts remaining")
    
    # 8. Unmerge back to draft
    print("\n8. UNMERGE MAIN → DRAFT")
    unmerged = await team_service.unmerge_to_draft(team_id, d1["id"], user_a)
    print(f"   ↩️  Unmerged: {unmerged['content'][:40]}... (space={unmerged['space']})")
    
    # 9. Get team detail (with members)
    print("\n9. TEAM DETAIL")
    detail = await team_service.get_team(team_id, user_a)
    print(f"   👥 Members: {len(detail['members'])}")
    for m in detail["members"]:
        print(f"      - {m['user_id']} ({m['role']})")
    
    # 10. Cleanup
    print("\n10. CLEANUP")
    await team_service.delete_team(team_id, user_a)
    print("   🗑️  Team deleted")
    
    print("\n" + "=" * 50)
    print("✅ ALL TESTS PASSED!")
    print("=" * 50)


asyncio.run(main())
