import os

def detect_framework():
    """
    Scans files to guess the framework and entrypoint.
    Returns: (framework_name, default_port, start_command) or (None, None, None)
    """
    # 1. FastAPI Scan
    if os.path.exists("main.py"):
        with open("main.py", "r") as f:
            content = f.read()
            if "FastAPI" in content:
                return "fastapi", 8000, "uvicorn main:app --host 0.0.0.0 --port 8000"

    # 2. Flask Scan
    if os.path.exists("app.py"):
         with open("app.py", "r") as f:
            content = f.read()
            if "Flask" in content:
                return "flask", 5000, "gunicorn app:app -b 0.0.0.0:5000"

    # No framework detected
    return None, None, None

def generate_deployment_assets(context):
    """
    Creates Dockerfile, docker-compose.yml, and Caddyfile
    if a web framework is detected.
    """
    framework, port, cmd = detect_framework()
    if not framework:
        return []

    generated = []
    print(f"   ✨ Web framework detected: {framework.upper()}. Generating deployment assets...")

    # --- 1. DOCKERFILE ---
    if not os.path.exists("Dockerfile"):
        # Use UV if detected, otherwise Pip
        install_cmd = "RUN pip install --no-cache-dir -r requirements.txt"
        if context.get("type") == "uv":
            # Assuming uv.lock or pyproject.toml is copied
            install_cmd = "RUN pip install uv && uv pip install --system -r requirements.txt"

        dockerfile_content = f"""# Generated by Xenfra
FROM python:3.11-slim

WORKDIR /app

# Install System Deps
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

# Copy all dependency definition files
COPY requirements.txt* .
COPY pyproject.toml* .
COPY uv.lock* .

# Install Python Deps
{install_cmd}

# Copy Code
COPY . .

# Expose Port
EXPOSE {port}

# Start Command
CMD ["/bin/sh", "-c", "{cmd}"]
"""
        with open("Dockerfile", "w") as f:
            f.write(dockerfile_content)
        generated.append("Dockerfile")

    # --- 2. CADDYFILE ---
    if not os.path.exists("Caddyfile"):
        caddy_content = f"""{{
    # Enable automatic HTTPS for all sites
    email your_email@example.com
}}

:443 {{
    reverse_proxy app:{port}
}}

:80 {{
    redir https://{{host}}{{uri}}
}}
"""
        with open("Caddyfile", "w") as f:
            f.write(caddy_content)
        generated.append("Caddyfile")

    # --- 3. DOCKER COMPOSE ---
    if not os.path.exists("docker-compose.yml"):
        compose_content = f"""
version: '3.8'

services:
  app:
    build: .
    container_name: xenfra_app
    restart: always
    # The internal port is exposed to other services in this network
    expose:
      - "{port}"

  caddy:
    image: caddy:latest
    container_name: xenfra_caddy
    restart: always
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - app

volumes:
  caddy_data:
  caddy_config:
"""
        with open("docker-compose.yml", "w") as f:
            f.write(compose_content)
        generated.append("docker-compose.yml")

    return generated