#!/usr/bin/env python3
"""Deep diagnostic: replicate exact server.py init_engine() flow."""
import os, sys
from pathlib import Path

MODEL_DIR = "/models/qwen3-tts"

print(f"cwd = {Path.cwd()}")
print(f"MODEL_DIR = {MODEL_DIR}")

# Replicate TTSEngine.__init__ path logic
project_root = Path.cwd()  # /home/ttsuser (WORKDIR)
model_dir = project_root / MODEL_DIR
print(f"project_root = {project_root}")
print(f"model_dir (resolved) = {model_dir}")

paths = {
    "talker_gguf": model_dir / "qwen3_tts_talker.q5_k.gguf",
    "predictor_gguf": model_dir / "qwen3_tts_predictor.q8_0.gguf",
    "decoder_onnx": model_dir / "qwen3_tts_decoder.fp16.onnx",
    "codec_enc_onnx": model_dir / "qwen3_tts_codec_encoder.fp16.onnx",
    "spk_enc_onnx": model_dir / "qwen3_tts_speaker_encoder.fp16.onnx",
    "tokenizer": model_dir / "tokenizer.json",
}

for name, p in paths.items():
    print(f"  {name}: {p} -> exists={p.exists()}")

# Check the missing files check
missing = [name for name, p in paths.items()
           if name in ["talker_gguf", "predictor_gguf", "decoder_onnx", "tokenizer"]
           and not p.exists()]
print(f"\nmissing = {missing}")

if not missing:
    print("\n=== Testing relative_to ===")
    for name in ["talker_gguf", "predictor_gguf"]:
        try:
            rel = paths[name].relative_to(project_root).as_posix()
            print(f"  {name} relative = {rel}")
        except ValueError as e:
            print(f"  {name} relative_to FAILED: {e}")

    print("\n=== Testing with chdir to parent ===")
    parent = os.path.dirname(MODEL_DIR)  # /models
    basename = os.path.basename(MODEL_DIR)  # qwen3-tts
    print(f"  parent={parent}, basename={basename}")
    os.chdir(parent)
    print(f"  new cwd = {Path.cwd()}")
    new_root = Path.cwd()
    new_model = new_root / basename
    for name in ["talker_gguf", "predictor_gguf"]:
        p = new_model / paths[name].name
        try:
            rel = p.relative_to(new_root).as_posix()
            print(f"  {name} relative = {rel} (exists={p.exists()})")
        except ValueError as e:
            print(f"  {name} relative_to FAILED: {e}")
