"""Streamlit frontend feature for NIKAME.

Generates a modern UI for RAG and AI interactions.
"""

from __future__ import annotations

from nikame.codegen.base import BaseCodegen, WiringInfo
from nikame.codegen.registry import register_codegen


@register_codegen
class StreamlitCodegen(BaseCodegen):
    """Generates a Streamlit playground for AI projects."""

    NAME = "streamlit"
    DESCRIPTION = "Streamlit UI for RAG and AI experimentation"
    DEPENDENCIES: list[str] = []
    MODULE_DEPENDENCIES: list[str] = []

    def generate(self) -> list[tuple[str, str]]:
        content = """import streamlit as st
import requests
import os

st.set_page_config(page_title="NIKAME Playground", page_icon="🤖", layout="wide")

st.title("🤖 NIKAME AI Playground")
st.markdown("---")

# Sidebar for configuration
st.sidebar.header("Configuration")
api_base = st.sidebar.text_input("API Base URL", value="http://localhost:8000/api/v1")

# Detect active integrations (simplified for generated stub)
tab1, tab2 = st.tabs(["📄 Document Ingest", "🔍 Ask Questions"])

with tab1:
    st.header("Upload Document")
    uploaded_file = st.file_uploader("Choose a file", type=["txt", "pdf", "md"])
    
    if uploaded_file and st.button("Ingest"):
        with st.spinner("Processing..."):
            files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
            try:
                response = requests.post(f"{api_base}/rag/upload", files=files)
                if response.status_code == 200:
                    st.success(f"Ingested! ID: {response.json().get('document_id')}")
                else:
                    st.error(f"Error: {response.text}")
            except Exception as e:
                st.error(f"Connection error: {e}")

with tab2:
    st.header("Search & Generate")
    question = st.text_input("Question:")
    if question and st.button("Query"):
        with st.spinner("Searching..."):
            try:
                response = requests.post(
                    f"{api_base}/rag/query", 
                    data={"question": question, "top_k": 3}
                )
                if response.status_code == 200:
                    st.markdown("### Response")
                    st.write(response.json().get("answer"))
                else:
                    st.error(f"Query failed: {response.text}")
            except Exception as e:
                st.error(f"Connection error: {e}")

st.sidebar.markdown("---")
st.sidebar.info("Generated by **NIKAME**")
"""

        dockerfile_content = (
            "FROM python:3.11-slim\n"
            "RUN pip install streamlit requests\n"
            "COPY . /app\n"
            "WORKDIR /app\n"
            "EXPOSE 8501\n"
            'CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]'
        )

        return [
            ("frontend/app.py", content),
            ("frontend/requirements.txt", "streamlit\nrequests\n"),
            ("frontend/Dockerfile", dockerfile_content)
        ]

    def wiring(self) -> WiringInfo:
        return WiringInfo(
            env_vars={"STREAMLIT_SERVER_PORT": "8501"}
        )
