import sys
import json
import os

def main() -> None:
 sys.stderr.write(f"DEBUG: mock_gemini_cli called with args: {sys.argv}\n")
 sys.stderr.write(f"DEBUG: GEMINI_CLI_HOOK_CONTEXT: {os.environ.get('GEMINI_CLI_HOOK_CONTEXT')}\n")
 sys.stderr.flush()

 if "--list-models" in sys.argv:
  print(json.dumps(["mock-model-1", "mock-model-2", "mock-model-3"]), flush=True)
  return

 mock_mode = os.environ.get("MOCK_MODE", "success")
 if mock_mode == "malformed_json":
  print("{broken_json: ", flush=True)
  sys.exit(1)
 elif mock_mode == "error_result":
  print(json.dumps({"type": "result", "status": "error", "error": "Mock simulated error"}), flush=True)
  sys.exit(1)
 elif mock_mode == "timeout":
  import time
  time.sleep(65)
  sys.exit(1)

 # Read prompt from stdin
 try:
  sys.stderr.write("DEBUG: mock_gemini_cli reading from stdin...\n")
  sys.stderr.flush()
  prompt = sys.stdin.read()
  sys.stderr.write(f"DEBUG: mock_gemini_cli read {len(prompt)} chars from stdin.\n")
  sys.stderr.flush()
  with open("mock_debug_prompt.txt", "a") as f:
   f.write(f"--- MOCK INVOKED ---\nARGS: {sys.argv}\nPROMPT:\n{prompt}\n------------------\n")
 except EOFError:
  prompt = ""
 except Exception:
  prompt = ""
 
 # Skip management commands
 if len(sys.argv) > 1 and sys.argv[1] in ["mcp", "extensions", "skills", "hooks"]:
  return

 # Check for multi-round integration test triggers
 is_resume = '--resume' in " ".join(sys.argv) or '"role": "tool"' in prompt or '"tool_call_id"' in prompt
 
 # 1. Check for specific MMA/Track triggers FIRST (these are most specific)
 if 'PATH: Epic Initialization' in prompt:
  mock_response = [
   {"id": "mock-track-1", "type": "Track", "module": "core", "persona": "Tech Lead", "severity": "Medium", "goal": "Mock Goal 1", "acceptance_criteria": ["criteria 1"], "title": "Mock Goal 1"},
   {"id": "mock-track-2", "type": "Track", "module": "ui", "persona": "Frontend Lead", "severity": "Low", "goal": "Mock Goal 2", "acceptance_criteria": ["criteria 2"], "title": "Mock Goal 2"}
  ]
  print(json.dumps({
   "type": "message",
   "role": "assistant",
   "content": json.dumps(mock_response)
  }), flush=True)
  print(json.dumps({
   "type": "result",
   "status": "success",
   "stats": {"total_tokens": 100, "input_tokens": 50, "output_tokens": 50},
   "session_id": "mock-session-epic"
  }), flush=True)
  return

 if 'PATH: Sprint Planning' in prompt or 'generate the implementation tickets' in prompt:
  mock_response = [
   {"id": "mock-ticket-1", "description": "Mock Ticket 1", "status": "todo", "assigned_to": "worker", "depends_on": []},
   {"id": "mock-ticket-2", "description": "Mock Ticket 2", "status": "todo", "assigned_to": "worker", "depends_on": ["mock-ticket-1"]}
  ]
  print(json.dumps({
   "type": "message",
   "role": "assistant",
   "content": json.dumps(mock_response)
  }), flush=True)
  print(json.dumps({
   "type": "result",
   "status": "success",
   "stats": {"total_tokens": 100, "input_tokens": 50, "output_tokens": 50},
   "session_id": "mock-session-sprint"
  }), flush=True)
  return

 # 2. Check for multi-round tool triggers
 is_resume_read = is_resume and 'read_file' in prompt
 is_resume_powershell = is_resume and 'run_powershell' in prompt

 if is_resume or 'Perform multi-round tool test' in prompt or 'Please read test.txt' in prompt or 'Deny me' in prompt:
  if not is_resume:
   # First round: emit tool call
   print(json.dumps({
    "type": "message",
    "role": "assistant",
    "content": "I need to check the directory first."
   }), flush=True)
   print(json.dumps({
    "type": "tool_use",
    "name": "run_powershell",
    "id": "mock-call-1",
    "args": {"script": "Get-ChildItem"}
   }), flush=True)
   print(json.dumps({
    "type": "result",
    "status": "success",
    "stats": {"total_tokens": 10, "input_tokens": 10, "output_tokens": 0},
    "session_id": "mock-session-default"
   }), flush=True)
   return
  else:
   # Second round
   if "USER REJECTED" in prompt:
    print(json.dumps({
     "type": "message",
     "role": "assistant",
     "content": "Tool execution was denied. I cannot proceed."
    }), flush=True)
   else:
    print(json.dumps({
     "type": "message",
     "role": "assistant",
     "content": "I have processed the tool results and here is the final answer."
    }), flush=True)
   print(json.dumps({
    "type": "result",
    "status": "success",
    "stats": {"total_tokens": 100, "input_tokens": 80, "output_tokens": 20},
    "session_id": "mock-session-final"
   }), flush=True)
   return

 # 3. Check for specific tool requests (these might match tool descriptions if not careful)
 # We check these AFTER the PATH triggers.
 if ('List the files in the current directory' in prompt or 'List the files' in prompt) and 'EPIC' not in prompt:
  print(json.dumps({
   "type": "message",
   "role": "assistant",
   "content": "I will list the files in the current directory."
  }), flush=True)
  print(json.dumps({
   "type": "tool_use",
   "name": "list_directory",
   "id": "mock-list-dir-call",
   "args": {"path": "."}
  }), flush=True)
  print(json.dumps({
   "type": "result",
   "status": "success",
   "stats": {"total_tokens": 10, "input_tokens": 5, "output_tokens": 5},
   "session_id": "mock-session-list-dir"
  }), flush=True)
  return

 if ('Read the first 10 lines' in prompt or is_resume_read) and 'EPIC' not in prompt:
  if not is_resume:
   print(json.dumps({
    "type": "message",
    "role": "assistant",
    "content": "I will read the first 10 lines of the file."
   }), flush=True)
   file_path = "src/aggregate.py"
   print(json.dumps({
    "type": "tool_use",
    "name": "read_file",
    "id": "mock-read-file-call",
    "args": {"path": file_path, "start_line": 1, "end_line": 10}
   }), flush=True)
   print(json.dumps({
    "type": "result",
    "status": "success",
    "stats": {"total_tokens": 10, "input_tokens": 5, "output_tokens": 5},
    "session_id": "mock-session-read-file"
   }), flush=True)
   return
  else:
   print(json.dumps({
    "type": "message",
    "role": "assistant",
    "content": "Here are the lines from the file: [Line 1, Line 2...]"
   }), flush=True)
   print(json.dumps({
    "type": "result",
    "status": "success",
    "stats": {"total_tokens": 20, "input_tokens": 10, "output_tokens": 10},
    "session_id": "mock-session-read-file-res"
   }), flush=True)
   return

 if ('Create a hello.ps1 script' in prompt or is_resume_powershell) and 'EPIC' not in prompt:
  if not is_resume:
   print(json.dumps({
    "type": "message",
    "role": "assistant",
    "content": "I will create the hello.ps1 script."
   }), flush=True)
   print(json.dumps({
    "type": "tool_use",
    "name": "run_powershell",
    "id": "mock-hello-call",
    "args": {"script": "Write-Output 'Simulation Test'"}
   }), flush=True)
   print(json.dumps({
    "type": "result",
    "status": "success",
    "stats": {"total_tokens": 10, "input_tokens": 5, "output_tokens": 5},
    "session_id": "mock-session-hello"
   }), flush=True)
   return
  else:
   print(json.dumps({
    "type": "message",
    "role": "assistant",
    "content": "Script hello.ps1 created successfully. Output: Simulation Test"
   }), flush=True)
   print(json.dumps({
    "type": "result",
    "status": "success",
    "stats": {"total_tokens": 20, "input_tokens": 10, "output_tokens": 10},
    "session_id": "mock-session-hello-res"
   }), flush=True)
   return

 # Default response
 content = "I am a mock CLI and I have processed your request."
 if 'Acknowledged' in prompt:
  content = "Acknowledged."
 elif 'What is the current date' in prompt:
  content = "The current date is March 1, 2026."

 print(json.dumps({
  "type": "message",
  "role": "assistant",
  "content": content
 }), flush=True)
 print(json.dumps({
  "type": "result",
  "status": "success",
  "stats": {"total_tokens": 50, "input_tokens": 25, "output_tokens": 25},
  "session_id": "mock-session-default"
 }), flush=True)

if __name__ == "__main__":
 main()
