#!/usr/bin/env python3
"""appflowy_start.py — Pre-create stub tables, then start AppFloyo Cloud."""

import subprocess, time, sys

PSQL = "/home/allaun/.nix-profile/bin/psql"
DB = [PSQL, "-h", "localhost", "-U", "postgres", "-d", "appflowy"]
ENV = {"PGPASSWORD": "postgres", "PATH": "/home/allaun/.nix-profile/bin:/usr/bin:/bin"}
ENV = {"PGPASSWORD": "postgres"}

def sql(cmd: str):
    subprocess.run(DB + ["-c", cmd], capture_output=True, env=ENV)

# Drop stale migration tracker
sql("DROP TABLE IF EXISTS auth._sqlx_migrations CASCADE")

# Pre-create tables that migrations reference out of order
sql("""
CREATE TABLE IF NOT EXISTS af_workspace (
    workspace_id UUID PRIMARY KEY,
    name TEXT NOT NULL DEFAULT '',
    owner_uid UUID NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    database_storage_id TEXT,
    workspace_type TEXT DEFAULT 'personal',
    icon TEXT,
    workspace_record_id UUID
)
""")
print("Pre-created af_workspace")

# Start AppFloyo Cloud
subprocess.run(["podman", "rm", "-f", "appflowy_fixer", "appflowy_cloud"],
               capture_output=True)

cid = subprocess.run(
    ["podman", "run", "-d", "--name", "appflowy_fixer",
     "--network", "host",
     "-e", "APPFLOWY_DATABASE_URL=postgres://postgres:postgres@localhost:5432/appflowy?sslmode=disable",
     "-e", "APPFLOWY_ENVIRONMENT=production",
     "-e", "APPFLOWY_REDIS_URI=redis://localhost:6379",
     "-e", "APPFLOWY_GOTRUE_JWT_SECRET=jwt_",
     "-e", "APPFLOWY_GOTRUE_JWT_EXP=3600",
     "-e", "APPFLOWY_GOTRUE_BASE_URL=http://localhost:9999",
     "-e", "APPFLOWY_BASE_URL=https://researchstack.info/appflowy",
     "-e", "APPFLOWY_WEB_URL=https://researchstack.info/appflowy",
     "-e", "APPFLOWY_ENCRYPTION_KEY=sk_encryption_key_at_least_32_chars_abcdef1234567890",
     "-e", "APPFLOWY_JWT_SECRET=jwt_",
     "-e", "APPFLOWY_CREATE_BUCKET=false",
     "-e", "APPFLOWY_S3_ENABLED=false",
     "-e", "APPFLOWY_SEARCH_ENABLED=false",
     "-e", "RUST_LOG=info",
     "docker.io/appflowyinc/appflowy_cloud:latest"],
    capture_output=True, text=True, timeout=30
).stdout.strip()

print(f"Started: {cid[:12]}")
time.sleep(20)

# Check result
logs = subprocess.run(["podman", "logs", "appflowy_fixer"],
                      capture_output=True, text=True, timeout=10)
health = subprocess.run(
    ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
     "http://localhost:8000/api/health"],
    capture_output=True, text=True, timeout=5
).stdout.strip()

if health == "200":
    subprocess.run(["podman", "rename", "appflowy_fixer", "appflowy_cloud"])
    print("✅ AppFloyo Cloud is UP!")
    sys.exit(0)

# Check for migration errors
for line in logs.stdout.split("\n"):
    if "error" in line.lower() or "Error" in line:
        print(f"  {line.strip()[:120]}")
sys.exit(1)
