#!/usr/bin/env python3
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path

PROMPT_TEMPLATE_PATH = Path(__file__).resolve().parent.parent / 'prompts' / 'remix-handoff.txt'


def fail(payload, code=1):
    print(json.dumps(payload, ensure_ascii=False))
    raise SystemExit(code)


def parse_args(argv):
    agent = ''
    folder_rel_path = ''
    entry_rel_path = ''
    session_name = ''
    i = 0
    while i < len(argv):
        arg = argv[i]
        if arg == '--agent' and i + 1 < len(argv):
            agent = argv[i + 1]
            i += 2
        elif arg == '--folder-rel-path' and i + 1 < len(argv):
            folder_rel_path = argv[i + 1]
            i += 2
        elif arg == '--entry-rel-path' and i + 1 < len(argv):
            entry_rel_path = argv[i + 1]
            i += 2
        elif arg == '--session' and i + 1 < len(argv):
            session_name = argv[i + 1]
            i += 2
        else:
            fail({'started': False, 'error': 'unknown_argument', 'message': f'未知参数: {arg}'})

    if not agent or not folder_rel_path or not entry_rel_path:
        fail({'started': False, 'error': 'missing_arguments', 'message': '请提供 --agent --folder-rel-path --entry-rel-path'})

    if not session_name:
        base_name = Path(folder_rel_path).name
        session_name = f"{datetime.now().strftime('%m%d')}_{base_name}_{datetime.now().strftime('%H%M')}"

    return agent, folder_rel_path, entry_rel_path, session_name


def run(cmd):
    return subprocess.run(cmd, capture_output=True, text=True)


def main():
    agent, folder_rel_path, entry_rel_path, session_name = parse_args(sys.argv[1:])

    if not PROMPT_TEMPLATE_PATH.exists():
        fail({'started': False, 'error': 'prompt_template_not_found', 'path': str(PROMPT_TEMPLATE_PATH)})

    prompt_template = PROMPT_TEMPLATE_PATH.read_text(encoding='utf-8')
    message = prompt_template.replace('{{FOLDER_REL_PATH}}', folder_rel_path).replace('{{ENTRY_REL_PATH}}', entry_rel_path)

    result = run(['mc', 'tui', agent, '--session', session_name, '--message', message])
    if result.returncode != 0:
        fail({'started': False, 'error': 'mc_tui_failed', 'agent': agent, 'session': session_name, 'details': result.stderr or result.stdout})

    print(json.dumps({
        'started': True,
        'agent': agent,
        'session': session_name,
        'folder_rel_path': folder_rel_path,
        'entry_rel_path': entry_rel_path,
        'message': message,
    }, ensure_ascii=False))


if __name__ == '__main__':
    main()
