import os
from pathlib import Path

def detect_framework():
    """
    Scans common Python project structures to guess the framework and entrypoint.
    Returns: (framework_name, default_port, start_command) or (None, None, None)
    """
    project_root = Path(os.getcwd())

    candidate_files = []
    
    # Check directly in project root
    for name in ["main.py", "app.py"]:
        if (project_root / name).is_file():
            candidate_files.append(project_root / name)

    # Check in src/*/ (standard package layout)
    for src_dir in project_root.glob("src/*"):
        if src_dir.is_dir():
            for name in ["main.py", "app.py"]:
                if (src_dir / name).is_file():
                    candidate_files.append(src_dir / name)

    for file_path in candidate_files:
        with open(file_path, "r") as f:
            content = f.read()
            
            module_name = str(file_path.relative_to(project_root)).replace(os.sep, '.')[:-3]
            # If path is like src/testdeploy/main.py, module_name becomes src.testdeploy.main
            # For uvicorn/gunicorn, we usually want package.module (e.g., testdeploy.main)
            if module_name.startswith("src."):
                # Strip the "src." prefix
                module_name = module_name[4:]


            if "FastAPI" in content:
                return "fastapi", 8000, f"uvicorn {module_name}:app --host 0.0.0.0 --port 8000"
            
            if "Flask" in content:
                return "flask", 5000, f"gunicorn {module_name}:app -b 0.0.0.0:5000"
    
    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
        if context.get("type") == "uv":
            install_cmd = "RUN pip install uv && uv pip install --system ."
        else:
            # Modern pip can install from pyproject.toml directly
            install_cmd = "RUN pip install ."

        dockerfile_content = f"""# Generated by Xenfra (Robust v2)
FROM python:3.13-slim

WORKDIR /app

# Install uv via pip
RUN pip install uv

# Copy only the dependency file first to leverage Docker layer caching
COPY pyproject.toml .

# Install dependencies from pyproject.toml
# This is more robust than `pip install .` as it doesn't build the local package
RUN uv pip install --system -r pyproject.toml

# Copy the rest of the application code
COPY . .

# Add the 'src' directory to Python's path
# This allows imports to work correctly for projects with a src/ layout
ENV PYTHONPATH="${{PYTHONPATH}}:/app/src"

# 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