"""Local character helper for the existing Windows Asset Forge / ComfyUI Desktop setup.
Run with system Python; install uses ComfyUI's own interpreter. No third-party
Python modules are needed by this wrapper. The actual models run in ComfyUI.
"""
import argparse
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
import uuid

HOME = Path.home()
FORGE = Path(__file__).resolve().parent
if not (FORGE / 'forge.py').is_file():
    FORGE = HOME / 'comfyui-text-to-3d-mcp'
MACHINE = json.loads((FORGE / 'machine.json').read_text(encoding='utf-8-sig'))
COMFY = Path(MACHINE.get('comfy_data') or HOME / 'Documents' / 'ComfyUI')
PY = Path(MACHINE.get('comfy_python') or COMFY / '.venv' / 'Scripts' / 'python.exe')
OUT = Path(MACHINE.get('comfy_output') or COMFY / 'output')
MODELS = Path(MACHINE.get('comfy_models') or COMFY / 'models')
NODES = Path(MACHINE.get('comfy_custom_nodes') or COMFY / 'custom_nodes')
API = MACHINE.get('comfy_url') or 'http://127.0.0.1:8000'
REPO = 'Aero-Ex/Hy-Motion1.0'


def run(*args, cwd=None, env=None):
    subprocess.run([str(a) for a in args], cwd=cwd, env=env, check=True)


def config():
    return json.loads((FORGE / 'machine.json').read_text(encoding='utf-8-sig'))


def request(path, body=None, timeout=30):
    data = None if body is None else json.dumps(body).encode('utf-8')
    req = urllib.request.Request(API + path, data=data, headers={'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            raw = r.read()
            return json.loads(raw) if raw else None
    except urllib.error.HTTPError as exc:
        raise RuntimeError(f'ComfyUI HTTP {exc.code}: {exc.read().decode(errors="replace")}') from exc


def require_nodes(*names):
    for name in names:
        if name not in (request('/object_info/' + name) or {}):
            raise RuntimeError(f'ComfyUI node not loaded: {name}. Check Desktop startup log and restart.')


def node(kind, **inputs):
    return {'class_type': kind, 'inputs': inputs}


def submit(graph, label):
    response = request('/prompt', {'prompt': graph, 'client_id': uuid.uuid4().hex})
    if response.get('node_errors'):
        raise RuntimeError(json.dumps(response['node_errors'], indent=2))
    pid = response['prompt_id']
    print(f'{label}: queued {pid}', flush=True)
    started = time.monotonic()
    next_report = started + 30
    while time.monotonic() - started < 3600:
        result = (request('/history/' + pid) or {}).get(pid)
        if result:
            status = result.get('status', {})
            if status.get('status_str') == 'error' or any(m[0] in ('execution_error','execution_interrupted') for m in status.get('messages', [])):
                errors = [m[1] for m in status.get('messages', []) if m[0] in ('execution_error','execution_interrupted')]
                raise RuntimeError(f'{label} failed: {json.dumps(errors or status, indent=2)}')
            if status.get('completed'):
                print(f'{label}: completed', flush=True)
                return result.get('outputs', {})
        if time.monotonic() >= next_report:
            print(f'{label}: still running / queued in ComfyUI', flush=True)
            next_report += 30
        time.sleep(3)
    raise RuntimeError(f'{label}: timed out waiting for {pid}; job may still be running.')


def release_vram():
    request('/free', {'unload_models': True, 'free_memory': True})
    time.sleep(2)


def install(resume=False):
    if not PY.is_file():
        raise RuntimeError(f'ComfyUI Desktop interpreter not found: {PY}')
    try:
        request('/system_stats', timeout=3)
    except (OSError, urllib.error.URLError):
        pass
    else:
        raise RuntimeError('Close ComfyUI Desktop before installing extensions.')
    nodes = NODES
    nodes.mkdir(parents=True, exist_ok=True)
    # Preserve the known working CUDA PyTorch build in the shared environment.
    pin_code = 'import importlib.metadata as m; print("\\n".join(d.metadata["Name"]+"=="+d.version for d in m.distributions() if d.metadata["Name"].lower() in {"torch","torchvision","torchaudio"}))'
    pins = subprocess.check_output([str(PY), '-c', pin_code], text=True)
    print('Preserving existing PyTorch packages:', pins, flush=True)
    with tempfile.TemporaryDirectory() as td:
        constraints = Path(td) / 'constraints.txt'
        constraints.write_text(pins, encoding='utf-8')
        env = os.environ.copy()
        env['PIP_CONSTRAINT'] = str(constraints)
        env['UV_CONSTRAINT'] = str(constraints)
        if not resume:
            for name, repo in [('ComfyUI-UniRig','PozzettiAndrea/ComfyUI-UniRig'), ('ComfyUI-HyMotion','Aero-Ex/ComfyUI-HyMotion')]:
                dest = nodes / name
                if not dest.exists():
                    run('git', 'clone', 'https://github.com/' + repo + '.git', dest)
                if not (dest / 'install.py').is_file():
                    raise RuntimeError(f'Missing installer in {dest}')
                if name == 'ComfyUI-UniRig':
                    run(PY, '-m', 'pip', 'install', '-r', 'requirements.txt', cwd=dest, env=env)
                run(PY, 'install.py', cwd=dest, env=env)
        else:
            print("Resuming: skipping installed extension dependencies.", flush=True)
        # The Windows FBX SDK may crash on DLL teardown. Only bypass teardown
        # after imports and a basic SDK manager create/destroy check succeed.
        run(PY, '-c', 'import os, fbx, torch; m=fbx.FbxManager.Create(); assert m is not None; m.Destroy(); print("FBX SDK probe OK; torch:", torch.__version__, flush=True); os._exit(0)')
        after = subprocess.check_output([str(PY), '-c', pin_code], text=True)
        if sorted(pins.splitlines()) != sorted(after.splitlines()):
            raise RuntimeError('PyTorch versions changed unexpectedly. Stop and inspect the install log.')
        marker = nodes / 'ComfyUI-UniRig' / '.yourunai-deps.json'
        marker.write_text(json.dumps({'python':str(PY),'pins':sorted(pins.lower().splitlines())}), encoding='utf-8')
    # Native HY-Motion adds its own model folder registration; make the specific
    # files visible to both the Desktop data tree and the application model tree.
    models = MODELS
    models.mkdir(parents=True, exist_ok=True)
    app_models = Path(config()['comfy_root']) / 'models'
    files = ['hymotion/HY-Motion-1.0/latest.ckpt',
             'text_encoders/clip-vit-large-patch14.safetensors',
             'text_encoders/Qwen3-8B_fp8.safetensors']
    code = 'from huggingface_hub import hf_hub_download; import sys; print(hf_hub_download(repo_id=sys.argv[1],filename=sys.argv[2],local_dir=sys.argv[3]))'
    for rel in files:
        dest = models / rel
        alt = app_models / rel
        if not dest.exists() and alt.is_file():
            dest.parent.mkdir(parents=True, exist_ok=True)
            try:
                os.link(alt, dest)
            except OSError:
                if input(f'Existing motion model cannot be linked across volumes. Copy {alt} to {dest}? [y/N] ').strip().lower() != 'y':
                    raise RuntimeError('Model copy declined; select the correct model directory.')
                if shutil.disk_usage(dest.parent).free < alt.stat().st_size + 1024**3:
                    raise RuntimeError('Insufficient space to copy model.')
                tmp = dest.with_name(dest.name + '.yourunai.part')
                shutil.copy2(alt, tmp)
                os.replace(tmp, dest)
        run(PY, '-c', code, REPO, rel, models)
        if not alt.exists():
            alt.parent.mkdir(parents=True, exist_ok=True)
            try:
                os.link(dest, alt)
            except OSError:
                print(f'Model stored in configured data directory: {dest}. No duplicate made across volumes; verify the Desktop model list.', flush=True)
    print('Install steps finished. Reopen ComfyUI Desktop and run finish or rig.')


def generate(name, prompt):
    if Path(name).name != name or not name or name in ('.','..'):
        raise ValueError('Use a simple asset name without directories.')
    run(sys.executable, FORGE / 'forge.py', 'asset', name, prompt,
        '-p','character_native','--preset','max','--set','tris=150000',
        '--set','shape_resolution=1536','--set','remesh_resolution=1024',
        '--set','shape_steps=30','--set','texture_steps=25', cwd=FORGE)
    result = FORGE / 'output' / (name + '.glb')
    if not result.is_file():
        raise RuntimeError(f'Generated GLB not found: {result}')
    return result


def matte(src, roughness, metallic):
    src = src.resolve(strict=True)
    dst = src.with_name(src.stem + '_matte.glb')
    if dst.exists():
        raise RuntimeError(f'Output already exists: {dst}. Rename it before retrying.')
    blender = Path(config()['blender'])
    # Preserve base color and normal maps. Constant values replace the original
    # roughness and metallic maps for this comparison copy only.
    code = f'''import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath={str(src)!r})
for mat in bpy.data.materials:
    if not mat.use_nodes or not mat.node_tree: continue
    for n in mat.node_tree.nodes:
        if n.type != 'BSDF_PRINCIPLED': continue
        for name, value in [('Metallic', {metallic!r}), ('Roughness', {roughness!r})]:
            sock = n.inputs[name]
            for link in list(sock.links): mat.node_tree.links.remove(link)
            sock.default_value = value
bpy.ops.export_scene.gltf(filepath={str(dst)!r}, export_format='GLB')
'''
    run(blender, '--background', '--factory-startup', '--python-exit-code', '1', '--python-expr', code)
    if not dst.is_file():
        raise RuntimeError('Blender did not export the comparison GLB.')
    print('Material comparison:', dst)
    return dst


def patch_unirig():
    # Change only the mesh path widget, retaining the original file loader.
    import re
    try:
        request('/system_stats', timeout=3)
    except (OSError, urllib.error.URLError):
        pass
    else:
        raise RuntimeError('Close ComfyUI Desktop before applying the UniRig patch.')
    path = NODES / 'ComfyUI-UniRig' / 'nodes' / 'mesh_io.py'
    text = path.read_text(encoding='utf-8-sig')
    old = r'io\.Combo\.Input\("file_path",\s*options=mesh_files,\s*tooltip="[^"\n]*"\)'
    new = 'io.String.Input("file_path", default="", tooltip="Absolute mesh file path or path relative to ComfyUI input/output.")'
    changed, count = re.subn(old, new, text)
    if count == 0:
        if new in text or re.search(r'io\.String\.Input\("file_path"', text):
            print('UniRig path patch already applied.')
            return
        raise RuntimeError(f'Expected UniRig mesh schema not found in {path}; no changes made.')
    if count != 1:
        raise RuntimeError('Unexpected number of matching widgets; no changes made.')
    compile(changed, str(path), 'exec')
    backup = path.with_name('mesh_io.py.assetforge.bak')
    if not backup.exists():
        shutil.copy2(path, backup)
    path.write_text(changed, encoding='utf-8')
    print(f'Patched {path} (backup: {backup}). Reopen ComfyUI Desktop.')


def rig(src, fingers=True):
    src = src.resolve(strict=True)
    require_nodes('UniRigLoadMesh','MIALoadModel','MIAAutoRig','UniRigPreviewRiggedMesh')
    info = request('/object_info/UniRigLoadMesh')['UniRigLoadMesh']
    spec = info.get('input', {}).get('required', {}).get('file_path') or info.get('input', {}).get('optional', {}).get('file_path')
    if not spec or spec[0] != 'STRING':
        raise RuntimeError(f'UniRig still advertises a non-string file_path widget. Close Desktop, run patch-unirig, and reopen. If already patched, check the loaded node location or cached schema. Reported schema: {spec!r}')
    name = src.stem + '_' + uuid.uuid4().hex[:8]
    release_vram()
    outputs = submit({'1':node('UniRigLoadMesh',source_folder='input',file_path=str(src)),
            '2':node('MIALoadModel',precision='fp32',attn_backend='auto'),
            '3':node('MIAAutoRig',trimesh=['1',0],model=['2',0],fbx_name=name+'_rigged',
                     no_fingers=not fingers,use_normal=False,reset_to_rest=True),
            '4':node('UniRigPreviewRiggedMesh',fbx_output_path=['3',0])}, 'MIA rig')
    filename = name + '_rigged_mia.fbx'
    candidates = [OUT / filename, Path(config()['comfy_root']) / 'output' / filename]
    for item in outputs.get('4',{}).get('fbx_file',[]):
        if isinstance(item,str):
            candidates.extend([Path(item), OUT / item, Path(config()['comfy_root']) / 'output' / item])
    result = next((p.resolve() for p in candidates if p.is_file()), None)
    if result is None:
        raise RuntimeError(f'Rigging returned success but FBX was not found. Checked {candidates}; history: {outputs}')
    print('Rigged FBX:', result, flush=True)
    return result


def animate(src, prompt, seconds, seed, device):
    src = src.resolve(strict=True)
    require_nodes('HYMotionDiTLoader','HYMotionTextEncoderLoader','HYMotionTextEncode','HYMotionSampler','HYMotionRetargetFBX')
    release_vram()
    name = src.stem + '_motion'
    outputs = submit({'1':node('HYMotionDiTLoader',model_name='HY-Motion-1.0',device='cuda'),
               '2':node('HYMotionTextEncoderLoader',clip_name='clip-vit-large-patch14.safetensors',llm_name='Qwen3-8B_fp8.safetensors',device=device),
               '3':node('HYMotionTextEncode',text_encoder=['2',0],text=prompt),
               '4':node('HYMotionSampler',dit_model=['1',0],text_embeds=['3',0],duration=seconds,seed=seed,num_samples=1,validation_steps=50,cfg_scale=5.0,sampler_method='euler'),
               '5':node('HYMotionRetargetFBX',motion_data=['4',0],target_fbx=str(src),output_dir='hymotion_retarget',filename_prefix=name,target_pose_type='T-Pose',fps=30.0,unique_names=True)}, 'HY-Motion animation')
    files = outputs.get('5',{}).get('fbx',[])
    results = [OUT / f.get('subfolder','') / f['filename'] for f in files if isinstance(f,dict) and 'filename' in f]
    if not results or not all(p.is_file() for p in results):
        raise RuntimeError('No exported animated FBX found in API history: '+json.dumps(outputs))
    for p in results: print('Animated FBX:',p,flush=True)
    return results


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    subs = ap.add_subparsers(dest='cmd', required=True)
    ins = subs.add_parser('install'); ins.add_argument('--resume', action='store_true')
    subs.add_parser('patch-unirig')
    g = subs.add_parser('generate'); g.add_argument('name'); g.add_argument('prompt')
    m = subs.add_parser('matte'); m.add_argument('file',type=Path); m.add_argument('--roughness',type=float,default=.65); m.add_argument('--metallic',type=float,default=.0)
    r = subs.add_parser('rig'); r.add_argument('file',type=Path); r.add_argument('--fingers',action='store_true',default=True); r.add_argument('--no-fingers',dest='fingers',action='store_false')
    for cmd in ('animate','finish','all'):
        p = subs.add_parser(cmd)
        if cmd == 'all': p.add_argument('name'); p.add_argument('prompt')
        else: p.add_argument('file',type=Path)
        p.add_argument('motion'); p.add_argument('--seconds',type=float,default=5); p.add_argument('--seed',type=int,default=42); p.add_argument('--encoder-device',choices=['cuda','cpu'],default='cuda')
        if cmd != 'animate': p.add_argument('--matte',action='store_true'); p.add_argument('--fingers',action='store_true',default=True); p.add_argument('--no-fingers',dest='fingers',action='store_false')
    a = ap.parse_args()
    if a.cmd == 'install': install(a.resume)
    elif a.cmd == 'patch-unirig': patch_unirig()
    elif a.cmd == 'generate': generate(a.name,a.prompt)
    elif a.cmd == 'matte':
        if not 0<=a.roughness<=1 or not 0<=a.metallic<=1: ap.error('Material values must be between 0 and 1.')
        matte(a.file,a.roughness,a.metallic)
    elif a.cmd == 'rig': rig(a.file,a.fingers)
    else:
        if not .5<=a.seconds<=12: ap.error('Motion duration must be between 0.5 and 12 seconds.')
        if a.cmd == 'animate': animate(a.file,a.motion,a.seconds,a.seed,a.encoder_device)
        else:
            src = generate(a.name,a.prompt) if a.cmd=='all' else a.file
            if a.matte: src = matte(src,.65,0.0)
            rigged = rig(src,a.fingers)
            animate(rigged,a.motion,a.seconds,a.seed,a.encoder_device)

if __name__ == '__main__':
    try: main()
    except (Exception, KeyboardInterrupt) as exc:
        print(f'ERROR: {exc}', file=sys.stderr); sys.exit(1)
