#!/usr/bin/env python3
from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path

WORKDIR = Path('/home/agent/projects/CryptoTradingBot/Crypto_Agent')
IDEAS_JOURNAL = WORKDIR / 'runtime/research/tradingview_community_ideas.jsonl'
EVAL_JOURNAL = WORKDIR / 'runtime/research/tradingview_community_idea_evaluations.jsonl'
COLLECT_CMD = [sys.executable, '-m', 'src.tools.tradingview_community_ideas', '--runtime-dir', 'runtime', '--limit-per-coin', '5']
EVAL_CMD = [sys.executable, '-m', 'src.tools.tradingview_community_track_record', '--runtime-dir', 'runtime']

def count_rows(path: Path) -> int:
    if not path.exists():
        return 0
    return sum(1 for line in path.read_text(encoding='utf-8', errors='replace').splitlines() if line.strip())

ideas_before = count_rows(IDEAS_JOURNAL)
evals_before = count_rows(EVAL_JOURNAL)
collect = subprocess.run(COLLECT_CMD, cwd=WORKDIR, text=True, capture_output=True, timeout=180)
if collect.returncode != 0:
    print('⚠️ TradingView Community Ideas Collector Fehler')
    print((collect.stderr or collect.stdout).strip()[-1000:])
    raise SystemExit(collect.returncode)
track = subprocess.run(EVAL_CMD, cwd=WORKDIR, text=True, capture_output=True, timeout=120)
if track.returncode != 0:
    print('⚠️ TradingView Community Track-Record Fehler')
    print((track.stderr or track.stdout).strip()[-1000:])
    raise SystemExit(track.returncode)

ideas_after = count_rows(IDEAS_JOURNAL)
evals_after = count_rows(EVAL_JOURNAL)
try:
    collect_data = json.loads(collect.stdout)
    track_data = json.loads(track.stdout)
except json.JSONDecodeError:
    print('⚠️ TradingView Community Watchdog JSON Fehler')
    print((collect.stdout + track.stdout).strip()[-1000:])
    raise SystemExit(1)

new_ideas = max(0, ideas_after - ideas_before)
new_evals = max(0, evals_after - evals_before)
summary = collect_data.get('summary') or {}
track_summary = track_data.get('summary') or {}
live_flags = int(summary.get('live_order_allowed_count') or 0)
errors = collect_data.get('errors') or {}

if new_ideas or new_evals or errors or live_flags:
    print('🧭 TradingView Community Research')
    print(f'new_ideas={new_ideas}, new_evaluations={new_evals}, total={summary.get("total", 0)}, bias={summary.get("by_bias", {})}')
    print(f'track_record_evaluated={track_summary.get("evaluated", 0)}, by_author={track_summary.get("by_author", {})}')
    print(f'mode=research_only, live_flags={live_flags}, errors={errors or "keine"}')
    print('Hinweis: Community-Ideen sind Kontext/Research, keine Trade-Autorität.')
