import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import uuid

# Import the registry path from server.py logic
REGISTRY_DIR = Path.home() / ".brynq"
REGISTRY_FILE = REGISTRY_DIR / "registry.json"

def get_registered_brokers() -> list[dict]:
    """Return all registered broker directories with metadata."""
    try:
        if not REGISTRY_FILE.exists():
            return []
        registry = json.loads(REGISTRY_FILE.read_text("utf-8"))
        brokers = []
        for path, meta in registry.get("brokers", {}).items():
            broker_dir = Path(path)
            if broker_dir.exists() and (broker_dir / "channels").exists():
                meta["broker_dir"] = str(broker_dir)
                brokers.append(meta)
        return brokers
    except (json.JSONDecodeError, OSError):
        return []

def resolve_broker_dir(target_project: str) -> Optional[Path]:
    """Find a broker directory by project name."""
    brokers = get_registered_brokers()
    for b in brokers:
        if b.get("project") == target_project:
            return Path(b["broker_dir"])
    return None

def post_cross_project(target_project: str, channel: str, message: str, sender_session: str, sender_name: str, platform: str) -> bool:
    """Post a message directly into another project's broker."""
    target_dir = resolve_broker_dir(target_project)
    if not target_dir:
        return False
        
    entry = {
        "id": uuid.uuid4().hex[:12],
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "session_id": sender_session,
        "session_name": sender_name,
        "platform": platform,
        "channel": channel,
        "msg_type": "cross_project",
        "message": f"[{target_project} via Cross-Project]: {message}",
    }
    
    target_channel_path = target_dir / "channels" / f"{channel}.jsonl"
    target_channel_path.parent.mkdir(parents=True, exist_ok=True)
    
    line = json.dumps(entry, default=str) + "\n"
    with target_channel_path.open("a", encoding="utf-8") as f:
        f.write(line)
        
    return True
