import json
import time
import os

STATE_FILE = "backtest_state.json"
SHADOW_FILE = "data/shadow-trades.json"

def fix():
    # Fix state
    try:
        with open(STATE_FILE, 'r') as f:
            state = json.load(f)
            
        if "progress_notes" not in state:
            state["progress_notes"] = []
            
        state["next_cursor_date"] = "2026-01-07 14:00:00"
        state["completed_through"] = "2026-01-07 03:30:00 UTC (11:30 WITA approx)"
        state["progress_notes"].append("Batch completed: Advanced M15 replay. Price created a bearish FVG at 4482.36 - 4479.115 and tapped into it around 11:15 UTC. Shadow observation of bearish continuation from this FVG.")
        
        with open(STATE_FILE, 'w') as f:
            json.dump(state, f, indent=2)
    except Exception as e:
        print(f"State fix error: {e}")

    # Fix shadows
    try:
        if not os.path.exists("data"):
            os.makedirs("data")
            
        shadows = []
        if os.path.exists(SHADOW_FILE):
            with open(SHADOW_FILE, 'r') as f:
                content = json.load(f)
                if isinstance(content, list):
                    shadows = content
                elif isinstance(content, dict) and "trades" in content:
                    shadows = content["trades"]

        new_shadow = {
            "id": f"shadow_{int(time.time())}",
            "timestamp": "2026-01-07 11:15:00 UTC",
            "symbol": "XAUUSD",
            "direction": "Short",
            "strategy": "Bearish FVG Retracement",
            "entry": 4479.115,
            "stop_loss": 4492.415,
            "take_profit": 4460.00,
            "outcome": "pending",
            "pnl_r": 0,
            "notes": "Price displaced down leaving an FVG (4482.36-4479.115). Tapped 4480.52 and rejected. Shadow entry at FVG bottom. Target is recent lows."
        }
        
        shadows.append(new_shadow)
        
        with open(SHADOW_FILE, 'w') as f:
            json.dump(shadows, f, indent=2)
            
    except Exception as e:
        print(f"Shadow fix error: {e}")

if __name__ == "__main__":
    fix()
    print("Fixed files.")
