import secrets
import random
from pathlib import Path

# === Prompt user input === #
react_api_url = input("🔧 Enter the REACT_APP_API_BASE_URL (e.g. https://minxa.wtf): ").strip()
allowed_origins = input("🔒 Enter allowed CORS origins for the backend comma-separated (e.g. https://minxa.lol,https://minxo.lol): ").strip()

# Ask for environment and validate input
valid_envs = ["dev", "stage", "prod"]
while True:
    environment = input("🌎 Enter environment (dev, stage, prod): ").strip().lower()
    if environment in valid_envs:
        break
    print("❌ Invalid input. Please enter one of: dev, stage, prod")

# === Backend values === #
db_user = "minxa"
db_password = secrets.token_urlsafe(16)
db_name = "minxadb"
db_host = "db"
db_port = 5432

hashids_salt = secrets.token_urlsafe(32)
alphabet = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789")
random.shuffle(alphabet)
encoder_alphabet = "".join(alphabet)

# === Generate backend .env === #
backend_env = f"""# Auto-generated backend .env

DATABASE_URL=postgresql+asyncpg://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}
ENVIRONMENT={environment}
HASHIDS_SALT={hashids_salt}
ENCODER_ALPHABET={encoder_alphabet}
ALLOWED_ORIGINS={allowed_origins}
"""

backend_env_path = Path("backend/.env")
backend_env_path.parent.mkdir(parents=True, exist_ok=True)
backend_env_path.write_text(backend_env)
print(f"✅ backend/.env written")

# === Generate frontend .env === #
frontend_env = f"""# Auto-generated frontend .env

REACT_APP_API_BASE_URL={react_api_url}
"""

frontend_env_path = Path("frontend/.env")
frontend_env_path.parent.mkdir(parents=True, exist_ok=True)
frontend_env_path.write_text(frontend_env)
print(f"✅ frontend/.env written")

# === Generate docker-compose.generated.yml === #
compose_yml = f"""
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: {db_user}
      POSTGRES_PASSWORD: {db_password}
      POSTGRES_DB: {db_name}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "{db_user}"]
      interval: 5s
      timeout: 5s
      retries: 5
    networks:
      - appnet

  backend:
    build:
      context: ./backend
    env_file:
      - ./backend/.env
    depends_on:
      db:
        condition: service_healthy
    ports:
      - "8000:8000"
    networks:
      - appnet

  frontend:
    build:
      context: ./frontend
    env_file:
      - ./frontend/.env
    depends_on:
      - backend
    ports:
      - "3000:80"
    networks:
      - appnet

volumes:
  postgres_data:

networks:
  appnet:
"""

compose_path = Path("docker-compose.generated.yml")
compose_path.write_text(compose_yml)
print(f"✅ docker-compose.generated.yml written")

print("\n🎉 All files generated! Run your stack with:\n")
print("docker compose -f docker-compose.generated.yml up --build")
