from __future__ import annotations

from typing import List, Dict, Optional

import streamlit as st
from ai_splitter.core import (
    BANNER,
    parse_input_text,
    generate_assessment_excel,
)


def main() -> None:
    st.set_page_config(
        page_title="CO Split-Up Generator",
        layout="centered",
    )

    st.title("CO Split-Up Generator")
    st.caption(
        f"{BANNER} · Powered by IPS Tech Community"
    )

    st.markdown("---")

    # Input mode: Upload or Paste
    input_mode = st.radio(
        "Input Mode",
        ["Upload CSV", "Paste table"],
        index=0,
        horizontal=True,
    )

    uploaded_file = None
    pasted_text = ""

    col_tmpl, col_input = st.columns([1, 2])

    with col_tmpl:
        # first 9 rows now have leading comma -> A blank, B label, C value
        template_csv = (
            ",SHEET INFO :,CO EVALUATION SHEET\n"
            ",Course Code :,C302\n"
            ",Course  Name :,PYTHON PROGRAM\n"
            ",Faculty Name :,SATHISH R\n"
            ",Academic Year :,2024-2025 (ODD)\n"
            ",Class :,B.TECH.IT (3RD YEAR 'A')\n"
            ",Regulation :,R2021 - AUC\n"
            ",Total No of Students :,63\n"
            ",ASSESSMENT NAME :,INTERNAL ASSESSMENT-1\n"
            "\n"
            "S.NO,REG. NO,NAME,MARKS\n"
            "1,21CSR001,Student Name,50\n"
        )
        st.download_button(
            label="⬇ Download input template",
            data=template_csv.encode("utf-8"),
            file_name="input_template.csv",
            mime="text/csv",
            help="Template: Row1–9 start at B & C (A blank); then S.NO table.",
        )

    with col_input:
        if input_mode == "Upload CSV":
            uploaded_file = st.file_uploader(
                "Upload CSV with header + students",
                type=["csv"],
            )
        else:
            pasted_text = st.text_area(
                "Paste data (header + students)",
                height=260,
                help="Keep row1–9 in B & C (A blank), then S.NO table from A.",
            )

    st.markdown("---")

    # -------- Parse CSV / pasted text & show editable header --------
    text: Optional[str] = None
    meta_labels: List[str] = []
    meta_values: List[str] = []
    students: List[Dict] = []
    edited_meta_values: List[str] = []

    if input_mode == "Upload CSV" and uploaded_file is not None:
        try:
            uploaded_file.seek(0)
            text = uploaded_file.read().decode("utf-8")
        except Exception as e:
            st.error(f"Error reading uploaded file: {e}")
    elif input_mode == "Paste table" and pasted_text.strip():
        text = pasted_text

    if text:
        try:
            meta_labels, meta_values, students = parse_input_text(text)
            st.markdown("### Header details (editable)")
            for i, label in enumerate(meta_labels):
                field_label = label or f"Field {i+1}"
                val = st.text_input(field_label, value=meta_values[i], key=f"meta_{i}")
                edited_meta_values.append(val)
        except Exception as e:
            st.error(f"Error parsing input: {e}")

    st.markdown("---")

    # Options
    col1, col2 = st.columns(2)
    with col1:
        reg = st.radio("Regulation", [13, 17, 21], index=2, horizontal=True)
    with col2:
        ass_label_to_value = {
            "IA1": 1,
            "IA2": 2,
            "MOD": 3,
            "LAB": 4,
            "PRO": 5,
            "CUS": 6,
        }
        ass_label = st.selectbox(
            "Assessment Type (short name)",
            list(ass_label_to_value.keys()),
            index=0,
        )
        ass = ass_label_to_value[ass_label]

    dep: Optional[int] = None
    custom_ms: Optional[List[int]] = None
    custom_co: Optional[List[int]] = None

    if ass == 3:
        dep_label = st.radio("Department (for MODEL)", ["S & H", "Other"], horizontal=True)
        dep = 1 if dep_label == "S & H" else 2

    # Custom assessment configuration
    if ass == 6:
        st.markdown("### Custom Assessment Configuration")
        q_count = st.number_input(
            "Number of Questions",
            min_value=1,
            max_value=100,
            value=5,
            step=1,
        )
        co_text = st.text_input(
            "CO number for each question (comma-separated)",
            value=",".join(str(i + 1) for i in range(min(q_count, 5))),
            help="Example for 5 questions: 1,2,3,4,5",
        )
        ms_text = st.text_input(
            "Max marks for each question (comma-separated)",
            value=",".join(["2"] * min(q_count, 5)),
            help="Example for 5 questions: 2,2,2,2,2",
        )

        try:
            co_list = [int(x.strip()) for x in co_text.split(",") if x.strip() != ""]
            ms_list = [int(x.strip()) for x in ms_text.split(",") if x.strip() != ""]
            if len(co_list) != q_count or len(ms_list) != q_count:
                st.warning(f"Provide exactly {q_count} CO numbers and {q_count} max marks.")
            else:
                custom_co = co_list
                custom_ms = ms_list
        except ValueError:
            st.warning("CO numbers and max marks must be integers separated by commas.")

    ass_name = st.text_input(
        "Output filename (without extension)",
        value="assessment_output",
        max_chars=50,
    )

    st.markdown("---")

    generate_btn = st.button("🚀 Generate CO Split-Up (Excel)", type="primary")

    if generate_btn:
        if text is None:
            st.error("Please upload a CSV file or paste data.")
        elif not ass_name.strip():
            st.error("Please enter a valid output filename.")
        elif ass == 6 and (custom_ms is None or custom_co is None):
            st.error("Please provide valid custom CO numbers and max marks.")
        elif not students:
            st.error("No valid student rows found. Check your input format.")
        else:
            try:
                # Use edited values if available, otherwise original
                final_meta_values = edited_meta_values or meta_values

                excel_bytes, filename = generate_assessment_excel(
                    meta_labels=meta_labels,
                    meta_values=final_meta_values,
                    students=students,
                    reg=reg,
                    ass=ass,
                    dep=dep,
                    ass_name=ass_name.strip(),
                    ass_short=ass_label,
                    custom_ms=custom_ms,
                    custom_co=custom_co,
                )

                st.success(
                    f"Generated CO evaluation sheet for {len(students)} students as '{filename}'."
                )

                st.download_button(
                    label="⬇ Download Excel",
                    data=excel_bytes,
                    file_name=filename,
                    mime=(
                        "application/vnd.openxmlformats-officedocument."
                        "spreadsheetml.sheet"
                    ),
                )
            except Exception as e:
                st.error(f"Error: {e}")


import os
import sys
import subprocess


def cli():
    """
    Entry point for the `ai-splitter` console script.
    This starts Streamlit in a new process.
    """
    script_path = os.path.abspath(__file__)
    subprocess.run([sys.executable, "-m", "streamlit", "run", script_path])


if __name__ == "__main__":
    # When you run: python app.py  OR  streamlit run app.py
    # just build the UI normally
    main()
