"""
Hermes Operations CLI
Directly callable by Hermes Agent (Miray, Sezen, Emre, Cemre, Cem) on ai.yungan.com
and synchronized with the Work PC (Intel i5-12400F + NVIDIA GeForce RTX 3070)
"""
import os
import sys
import io
import json
import argparse
from datetime import datetime

# UTF-8 stdout
if sys.stdout.encoding != 'utf-8':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(CURRENT_DIR) if os.path.basename(CURRENT_DIR) == 'tools' else CURRENT_DIR

for p in [PROJECT_ROOT, CURRENT_DIR]:
    if p not in sys.path:
        sys.path.insert(0, p)

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from engine.script_generator import generate_bible_short_script, generate_bible_long_script, generate_comment_reply

def find_token_file():
    possible_paths = [
        os.path.join(PROJECT_ROOT, 'credentials', 'token_holybible.json'),
        os.path.join(CURRENT_DIR, 'credentials', 'token_holybible.json'),
        "/opt/data/ai/credentials/token_holybible.json",
        "/home/yunganc/.hermes/ai/credentials/token_holybible.json",
        "/home/yunganc/public_html/ai/credentials/token_holybible.json"
    ]
    for p in possible_paths:
        if os.path.exists(p):
            return p
    return possible_paths[0]

def get_queue_dirs():
    dirs = [os.path.join(PROJECT_ROOT, 'queue')]
    for extra in ["/opt/data/ai/queue", "/home/yunganc/.hermes/ai/queue", "/home/yunganc/public_html/ai/queue"]:
        parent = os.path.dirname(extra)
        if os.path.exists(parent) and extra not in dirs:
            dirs.append(extra)
    for d in dirs:
        try:
            os.makedirs(d, exist_ok=True)
        except Exception:
            pass
    return dirs

def get_youtube_service():
    token_path = find_token_file()
    if not os.path.exists(token_path):
        raise FileNotFoundError(f"Token file not found. Checked: {token_path}")
    with open(token_path, 'r', encoding='utf-8') as f:
        token_data = json.load(f)
    creds = Credentials.from_authorized_user_info(token_data)
    return build('youtube', 'v3', credentials=creds)

def action_channel_info():
    yt = get_youtube_service()
    res = yt.channels().list(part="snippet,statistics,contentDetails", mine=True).execute()
    item = res['items'][0]
    stats = item['statistics']
    snippet = item['snippet']
    uploads_id = item['contentDetails']['relatedPlaylists']['uploads']

    videos = yt.playlistItems().list(part="snippet", playlistId=uploads_id, maxResults=5).execute()
    recent = []
    for v in videos.get('items', []):
        vid_id = v['snippet']['resourceId']['videoId']
        recent.append({
            "title": v['snippet']['title'],
            "published": v['snippet']['publishedAt'],
            "videoId": vid_id,
            "url": f"https://youtube.com/watch?v={vid_id}"
        })

    report = {
        "channel_title": snippet['title'],
        "channel_id": item['id'],
        "subscribers": stats.get('subscriberCount', 0),
        "total_views": stats.get('viewCount', 0),
        "total_videos": stats.get('videoCount', 0),
        "recent_videos": recent
    }
    print(json.dumps(report, indent=2, ensure_ascii=False))

def action_generate_script(theme: str, video_type: str = "short"):
    if video_type == "long":
        script = generate_bible_long_script(theme)
    else:
        script = generate_bible_short_script(theme)
    print(json.dumps(script, indent=2, ensure_ascii=False))

def action_list_comments():
    yt = get_youtube_service()
    try:
        res = yt.commentThreads().list(
            part="snippet",
            allThreadsRelatedToChannelId="UC6JqghFL24L_D6Zdu4NtbZQ",
            maxResults=10,
            order="time"
        ).execute()
        comments = []
        for item in res.get('items', []):
            top = item['snippet']['topLevelComment']['snippet']
            comments.append({
                "author": top['authorDisplayName'],
                "text": top['textDisplay'],
                "comment_id": item['id'],
                "video_id": item['snippet'].get('videoId', ''),
                "reply_count": item['snippet'].get('totalReplyCount', 0),
                "published": top['publishedAt']
            })
        print(json.dumps({"comments": comments}, indent=2, ensure_ascii=False))
    except Exception as e:
        print(json.dumps({"error": str(e), "comments": []}))

def action_reply_comment(comment_id: str, text: str):
    yt = get_youtube_service()
    body = {
        'snippet': {
            'parentId': comment_id,
            'textOriginal': text
        }
    }
    yt.comments().insert(part="snippet", body=body).execute()
    print(json.dumps({"status": "replied", "comment_id": comment_id, "text": text}, ensure_ascii=False))

def action_queue_video(theme: str, video_type: str = "short"):
    if video_type == "long":
        script = generate_bible_long_script(theme)
    else:
        script = generate_bible_short_script(theme)

    job_id = datetime.now().strftime("%Y%m%d_%H%M%S")
    job_payload = {
        "job_id": job_id,
        "video_type": video_type,
        "theme": theme,
        "script": script,
        "status": "pending",
        "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "target_workstation": "İş Bilgisayarı (i5-12400F + RTX 3070)"
    }
    for qdir in get_queue_dirs():
        try:
            job_file = os.path.join(qdir, f"job_{job_id}.json")
            with open(job_file, 'w', encoding='utf-8') as f:
                json.dump(job_payload, f, indent=2, ensure_ascii=False)
        except Exception:
            pass

    print(json.dumps({
        "status": "queued",
        "job_id": job_id,
        "video_type": video_type,
        "theme": theme,
        "title": script['title'],
        "workstation": "İş Bilgisayarı (i5-12400F + RTX 3070 NVENC)"
    }, indent=2, ensure_ascii=False))

def action_list_queue():
    qdirs = get_queue_dirs()
    seen = {}
    for qdir in qdirs:
        if not os.path.exists(qdir):
            continue
        for fname in sorted(os.listdir(qdir), reverse=True):
            if fname.startswith("job_") and fname.endswith(".json") and fname not in seen:
                try:
                    with open(os.path.join(qdir, fname), 'r', encoding='utf-8') as f:
                        data = json.load(f)
                        seen[fname] = {
                            "job_id": data.get("job_id"),
                            "video_type": data.get("video_type", "short"),
                            "theme": data.get("theme"),
                            "title": data.get("script", {}).get("title", ""),
                            "status": data.get("status"),
                            "video_url": data.get("video_url", ""),
                            "completed_at": data.get("completed_at", "")
                        }
                except Exception:
                    pass
    print(json.dumps({"jobs": list(seen.values())}, indent=2, ensure_ascii=False))

def action_local_status():
    for path in [
        os.path.join(PROJECT_ROOT, "queue", "workstation_status.json"),
        "/opt/data/ai/queue/workstation_status.json",
        "/home/yunganc/.hermes/ai/queue/workstation_status.json"
    ]:
        if os.path.exists(path):
            with open(path, "r", encoding="utf-8") as f:
                print(f.read())
                return
    print(json.dumps({
        "workstation": "İş Bilgisayarı (Intel Core i5-12400F + NVIDIA GeForce RTX 3070)",
        "status": "online",
        "local_models": ["llama3.2:3b"]
    }, indent=2, ensure_ascii=False))

def main():
    parser = argparse.ArgumentParser(description="Hermes Operations CLI")
    subparsers = parser.add_subparsers(dest="action")

    subparsers.add_parser("channel-info")

    script_parser = subparsers.add_parser("generate-script")
    script_parser.add_argument("--theme", type=str, default="faith and peace in anxiety")
    script_parser.add_argument("--type", type=str, default="short", choices=["short", "long"])

    subparsers.add_parser("list-comments")

    reply_parser = subparsers.add_parser("reply-comment")
    reply_parser.add_argument("--id", type=str, required=True)
    reply_parser.add_argument("--text", type=str, required=True)

    queue_parser = subparsers.add_parser("queue-short")
    queue_parser.add_argument("--theme", type=str, default="God never leaves you")

    queue_long_parser = subparsers.add_parser("queue-long")
    queue_long_parser.add_argument("--theme", type=str, default="Overcoming Fear Through God's Promises")

    subparsers.add_parser("list-queue")
    subparsers.add_parser("local-status")

    args = parser.parse_args()

    if args.action == "channel-info":
        action_channel_info()
    elif args.action == "generate-script":
        action_generate_script(args.theme, args.type)
    elif args.action == "list-comments":
        action_list_comments()
    elif args.action == "reply-comment":
        action_reply_comment(args.id, args.text)
    elif args.action == "queue-short":
        action_queue_video(args.theme, "short")
    elif args.action == "queue-long":
        action_queue_video(args.theme, "long")
    elif args.action == "list-queue":
        action_list_queue()
    elif args.action == "local-status":
        action_local_status()
    else:
        parser.print_help()

if __name__ == '__main__':
    main()
