import asyncio
import json
import subprocess
from pathlib import Path

import auto_trader

BASE = Path('/home/arin/.openclaw/workspace/projects/auto-trader')
PY = '/home/arin/.openclaw/workspace/KIS_MCP_Server/.venv/bin/python'


def load_config():
    return auto_trader.load_json(auto_trader.CONFIG_PATH, {})


def run_notifier():
    subprocess.run([PY, str(BASE / 'notify_telegram.py')], check=False)


async def main():
    while True:
        try:
            result = await auto_trader.run_once()
            print(json.dumps(result, ensure_ascii=False), flush=True)
            run_notifier()
        except Exception as e:
            print(json.dumps({'error': str(e)}, ensure_ascii=False), flush=True)
        cfg = load_config()
        await asyncio.sleep(int(cfg.get('poll_seconds', 60)))


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