#!/usr/bin/env python3
"""Deploy Anytype Sync Server on neon-64gb."""
import subprocess, os, tempfile, json

HOST = "allaun@100.92.88.64"

def sh(cmd, timeout=60):
    r = subprocess.run(["ssh", "-o", "ConnectTimeout=10", HOST, cmd],
                       capture_output=True, text=True, timeout=timeout)
    out = r.stdout.strip()[:300]
    err = r.stderr.strip()[:200]
    if out: print(f"  {out}")
    if err: print(f"  ! {err}")
    return r.returncode == 0

def scp_put(content, remote_path):
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
        f.write(content)
        lpath = f.name
    subprocess.run(["scp", lpath, f"{HOST}:{remote_path}"],
                   capture_output=True, timeout=30)
    os.unlink(lpath)

print("=== 1. Install any-sync-network ===")
sh("""
curl -sL https://github.com/anyproto/any-sync-tools/releases/download/v0.6.1/any-sync-tools-0.6.1.linux-arm64.tgz -o /tmp/any-sync-tools.tgz
tar xzf /tmp/any-sync-tools.tgz -C /tmp/
sudo cp /tmp/any-sync-network /usr/local/bin/ 2>/dev/null || cp /tmp/any-sync-network ~/.local/bin/ 2>/dev/null || true
export PATH=$PATH:$HOME/.local/bin
which any-sync-network
""")

print("=== 2. Generate configs ===")
sh("mkdir -p /home/allaun/any-sync-config")

default_template = """external-addresses:
 - 100.92.88.64

any-sync-coordinator:
  listen: 0.0.0.0
  yamuxPort: 4830
  quicPort: 5830
  mongo:
    connect: mongodb://localhost:27017
    database: coordinator
  defaultLimits:
    spaceMembersRead: 1000
    spaceMembersWrite: 1000
    sharedSpacesLimit: 1000

any-sync-consensusnode:
  listen: 0.0.0.0
  yamuxPort: 4530
  quicPort: 5530
  mongo:
    connect: mongodb://localhost:27017/?w=majority
    database: consensus

any-sync-filenode:
  listen: 0.0.0.0
  yamuxPort: 4730
  quicPort: 5730
  s3Store:
    endpoint: http://localhost:9000
    bucket: anytype
    indexBucket: anytype-index
    region: us-east-1
    profile: default
    forcePathStyle: true
  redis:
    url: redis://localhost:6379?dial_timeout=3&read_timeout=6s
  defaultLimit: 1099511627776

any-sync-node:
  listen:
  - 0.0.0.0
  yamuxPort:
  - 4430
  quicPort:
  - 5430
"""

scp_put(default_template, "/home/allaun/any-sync-config/defaultTemplate.yml")

print("=== 3. Generate auto config ===")
sh("""
export PATH=$PATH:$HOME/.local/bin
any-sync-network create --auto --conf /home/allaun/any-sync-config/defaultTemplate.yml --dir /home/allaun/any-sync-config 2>&1 || true
ls -la /home/allaun/any-sync-config/
""")

print("=== 4. Start MongoDB (replica set) ===")
sh("""
podman rm -f anytype-mongo 2>/dev/null
podman run -d --name anytype-mongo --network host \
  docker.io/mongo:7  --replSet rs0 --bind_ip 0.0.0.0 2>&1
""")

subprocess.run(["sleep", "10"])

print("=== 5. Init MongoDB replica set ===")
sh('''
podman exec anytype-mongo mongosh --quiet --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})' 2>&1 | head -5
''')

print("=== 6. Start Coordinator ===")
sh("""
podman rm -f any-sync-coordinator 2>/dev/null
podman run -d --name any-sync-coordinator --network host \
  -v /home/allaun/any-sync-config:/etc/any-sync:ro \
  docker.io/anyproto/any-sync-coordinator:v0.9.1
""")

print("=== 7. Start Sync Node ===")
sh("""
podman rm -f any-sync-node-1 2>/dev/null
podman run -d --name any-sync-node-1 --network host \
  -v /home/allaun/any-sync-config:/etc/any-sync:ro \
  docker.io/anyproto/any-sync-node:v0.11.1
""")

subprocess.run(["sleep", "10"])

print("=== Status ===")
sh("podman ps --format 'table {{.Names}}\t{{.Status}}'")
sh("podman logs any-sync-coordinator 2>&1 | tail -3")
sh("podman logs any-sync-node-1 2>&1 | tail -3")
