import platform
import asyncio
from playwright.async_api import async_playwright
import argparse
import os
from datetime import datetime
from pathlib import Path

async def monitor_stream(log_path, domain):
    async with async_playwright() as p:
        browser = await p.chromium.connect_over_cdp("http://localhost:9222")
        while True:
            contexts = browser.contexts
            for context in contexts:
                for page in context.pages:
                    if domain in  page.url:
                        print(f"Found Streamate tab")
                        await monitor_requests(page, log_path)
            
            await asyncio.sleep(5)  # Check every 5 seconds

async def monitor_requests(page, log_path):
    async def log_request(request):
        if request.resource_type not in ['document', 'image', 'font', 'stylesheet']:
            log_entry = f"[{datetime.now()}] Request: {request.method} {request.url}\n"
            with open(log_path, 'a') as f:
                f.write(log_entry)

    async def log_response(response):
        #print(await response.body())
        #print(response.request.resource_type)
        #if response.request.resource_type not in ['document', 'image', 'font', 'stylesheet']:
        if response.request.resource_type in ['xhr'] and not response.url.endswith(".mp3"):
            log_entry = f"[{datetime.now()}] Response: {response.status} {response.url} -> BODY: "
            log_body = await response.body()
            with open(log_path, 'a') as f:
                f.write(log_entry)
                print(log_body)
                f.write(str(log_body))
                f.write("\n\n")

    async def log_websocket(ws):
        def writelog(payload, origin, url):
           print(origin+": "+str(payload)+"\n")
           log_entry = f"[{datetime.now()}] WS: {origin} {url} -> Message: "
           with open(log_path, 'a') as f:
               f.write(log_entry)
               f.write(origin+": ")
               f.write(str(payload)+"\n\n")

        print(f"WebSocket opened: {ws.url}")
        ws.on("framesent", lambda payload: writelog(payload, 'framesent', ws.url))
        ws.on("framereceived", lambda payload: writelog( payload, 'framereceived', ws.url))
        ws.on("close", lambda payload: print("WebSocket closed"))

    page.on("request", log_request)
    page.on("response", log_response)
    page.on("websocket", log_websocket)

    while True:
        await asyncio.sleep(1)

if __name__ == "__main__":
    lpath=str(Path(Path.home(), Path('streamon.log')))

    parser = argparse.ArgumentParser(description="Monitor Streamate requests")
    parser.add_argument("--log_path", type=str, default=lpath,
                        help="Path to the log file")
    parser.add_argument("--domain", type=str, default="performerclient.streamatemodels.com",
                        help="URL to monitor")
    args = parser.parse_args()

    
    log_dir = os.path.dirname(args.log_path)
    if log_dir and not os.path.exists(log_dir):
        os.makedirs(log_dir)

    asyncio.run(monitor_stream(args.log_path, args.domain))
