import os
import json
import glob
from pathlib import Path

brain_dir = r"C:\Users\Abhiram P M\.gemini\antigravity-ide\brain"

# Get all transcript paths with their creation time to sort chronologically
transcripts = []
for d in os.listdir(brain_dir):
    log_path = os.path.join(brain_dir, d, ".system_generated", "logs", "transcript_full.jsonl")
    if os.path.exists(log_path):
        transcripts.append((os.path.getctime(log_path), log_path))

transcripts.sort(key=lambda x: x[0])

file_states = {}

for _, log_path in transcripts:
    with open(log_path, "r", encoding="utf-8") as f:
        for line in f:
            try:
                step = json.loads(line)
                
                # Check for tool_calls
                if "tool_calls" in step:
                    for call in step["tool_calls"]:
                        func = call.get("function", {})
                        name = func.get("name", "")
                        args = func.get("arguments", {})
                        if isinstance(args, str):
                            try:
                                args = json.loads(args)
                            except:
                                continue
                        
                        target_file = args.get("TargetFile", "")
                        if not target_file.lower().endswith(".html"):
                            continue
                            
                        # Normalize path
                        target_file = target_file.replace("/", "\\")
                        if "Franciscan Society" not in target_file:
                            continue
                        
                        filename = os.path.basename(target_file)
                        
                        if name == "default_api:write_to_file":
                            content = args.get("CodeContent", "")
                            if content:
                                file_states[filename] = content
                                
                        elif name == "default_api:replace_file_content" or name == "default_api:multi_replace_file_content":
                            if filename not in file_states:
                                continue
                                
                            content = file_states[filename]
                            
                            if name == "default_api:replace_file_content":
                                chunks = [{
                                    "TargetContent": args.get("TargetContent", ""),
                                    "ReplacementContent": args.get("ReplacementContent", ""),
                                }]
                            else:
                                chunks = args.get("ReplacementChunks", [])
                                
                            for chunk in chunks:
                                target = chunk.get("TargetContent", "")
                                replacement = chunk.get("ReplacementContent", "")
                                if target and target in content:
                                    content = content.replace(target, replacement)
                                    
                            file_states[filename] = content
            except Exception as e:
                pass

# Now write them to a recovery directory
os.makedirs("recovered_html", exist_ok=True)
for filename, content in file_states.items():
    if content.strip():
        with open(os.path.join("recovered_html", filename), "w", encoding="utf-8") as f:
            f.write(content)
        print(f"Recovered {filename} ({len(content)} bytes)")
