import asyncio
import json
import os
import sys
from pathlib import Path


PLUGIN_DIR = Path(
    r"C:\Users\darsh.shah\.codex\plugins\cache\openai-curated\gpt-researcher\f78e3ad49297672a905eb7afb6aa0cef34edc79e"
)
ENV_FILE = PLUGIN_DIR / ".env"
SERVER_DIR = PLUGIN_DIR / "vendor" / "gptr-mcp"

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except AttributeError:
    pass


def load_env() -> None:
    for line in ENV_FILE.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        os.environ[key] = value


async def main() -> None:
    load_env()
    sys.path.insert(0, str(SERVER_DIR))
    os.chdir(SERVER_DIR)

    from gpt_researcher import GPTResearcher

    mode = sys.argv[1] if len(sys.argv) > 1 else "quick"
    query = (
        sys.argv[2]
        if len(sys.argv) > 2
        else "What are the best arguments against persistent LLM memory systems?"
    )
    researcher = GPTResearcher(query)

    if mode == "quick":
        result = await researcher.quick_search(query=query)
        print(type(result).__name__)
        print(str(result)[:4000])
        return

    if mode == "deep":
        await researcher.conduct_research()
        context = researcher.get_research_context()
        sources = researcher.get_research_sources()
        source_urls = researcher.get_source_urls()
        print(f"context_length={len(context)}")
        print(f"source_count={len(sources)}")
        print(f"url_count={len(source_urls)}")
        print(context[:4000])
        return

    if mode == "deepjson":
        await researcher.conduct_research()
        context = researcher.get_research_context()
        sources = researcher.get_research_sources()
        source_urls = researcher.get_source_urls()
        payload = {
            "query": query,
            "context": context,
            "sources": sources,
            "source_urls": source_urls,
        }
        output_path = Path(sys.argv[3]) if len(sys.argv) > 3 else None
        if output_path:
            output_path.write_text(
                json.dumps(payload, ensure_ascii=False, indent=2),
                encoding="utf-8",
            )
            print(str(output_path))
        else:
            print(json.dumps(payload, ensure_ascii=False))
        return

    raise SystemExit(f"Unknown mode: {mode}")


if __name__ == "__main__":
    asyncio.run(main())
