import os
import time
import math
import json
import requests
import pandas as pd
import streamlit as st
from typing import Dict, Any, Optional

ATTIO_API_BASE = "https://api.attio.com/v2/notes"

# ---------------------------
# Utilities
# ---------------------------

def make_session(token: str) -> requests.Session:
    s = requests.Session()
    s.headers.update({
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    })
    return s

def safe_iso(val: Any) -> Optional[str]:
    if val is None or (isinstance(val, float) and math.isnan(val)):
        return None
    s = str(val).strip()
    return s if s else None

def to_bool(val: Any) -> bool:
    if isinstance(val, bool):
        return val
    if val is None:
        return False
    return str(val).strip().lower() in {"1", "true", "yes", "y"}

def post_with_retry(session: requests.Session, payload: Dict[str, Any], max_retries: int = 5) -> requests.Response:
    delay = 1.0
    for attempt in range(max_retries):
        try:
            resp = session.post(ATTIO_API_BASE, json=payload, timeout=30)
            # Retry on rate limit or server errors
            if resp.status_code in (429, 500, 502, 503, 504):
                # Respect Retry-After if present
                retry_after = resp.headers.get("Retry-After")
                sleep_for = float(retry_after) if retry_after else delay
                time.sleep(sleep_for)
                delay = min(delay * 2, 30)  # exponential backoff up to 30s
                continue
            return resp
        except requests.RequestException as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(delay)
            delay = min(delay * 2, 30)
    # Should not reach here
    return resp  # type: ignore

def build_note_payload(
    parent_object: str,
    parent_record_id: str,
    title: str,
    content: str,
    content_format_default: str,
    format_col_val: Optional[str],
    created_at: Optional[str],
    meeting_id: Optional[str],
) -> Dict[str, Any]:
    fmt = (format_col_val or content_format_default or "plaintext").strip().lower()
    if fmt not in {"plaintext", "markdown"}:
        fmt = "plaintext"

    data = {
        "data": {
            "parent_object": parent_object.strip(),
            "parent_record_id": parent_record_id.strip(),
            "title": title.strip(),
            "format": fmt,
            "content": content if isinstance(content, str) else str(content),
        }
    }
    if created_at:
        data["data"]["created_at"] = created_at
    if meeting_id:
        data["data"]["meeting_id"] = meeting_id
    return data

# ---------------------------
# Streamlit UI
# ---------------------------

st.set_page_config(page_title="Attio Notes Uploader", page_icon="📝", layout="wide")
st.title("📝 Attio Notes Uploader")

st.markdown(
    """
Upload a CSV and create notes in Attio for each row.

**Required CSV columns:** `parent_object`, `parent_record_id`, `title`, `content`  
**Optional:** `format` (`plaintext` or `markdown`), `created_at` (ISO8601), `meeting_id` (UUID)
"""
)

with st.sidebar:
    st.header("Authentication")
    token = st.text_input(
        "Attio API Token (Bearer)",
        value=os.getenv("ATTIO_API_TOKEN", ""),
        type="password",
        help="Token must have scopes: note:read-write, object_configuration:read, record_permission:read."
    )
    st.header("Defaults & Options")
    default_format = st.selectbox(
        "Default note format (used if CSV has no 'format' column or value)",
        options=["plaintext", "markdown"],
        index=0
    )
    dry_run = st.checkbox("Dry run (no API calls)", value=True, help="Preview mapping and rows without creating notes.")
    max_rows = st.number_input("Max rows to process (0 = all)", min_value=0, value=0, step=1)
    st.caption("Tip: leave Dry run on to validate before sending.")

uploaded = st.file_uploader("Upload CSV", type=["csv"])

if uploaded:
    try:
        df = pd.read_csv(uploaded)
    except Exception as e:
        st.error(f"Failed to read CSV: {e}")
        st.stop()

    st.subheader("CSV Preview")
    st.dataframe(df.head(20))

    # Column mapping (flexible names)
    st.subheader("Map Columns")
    cols = ["(none)"] + list(df.columns)

    def picker(label, default_name):
        # auto-select if the default exists
        idx = cols.index(default_name) if default_name in df.columns else 0
        return st.selectbox(label, options=cols, index=idx)

    col_parent_object = picker("parent_object column", "parent_object")
    col_parent_record_id = picker("parent_record_id column", "parent_record_id")
    col_title = picker("title column", "title")
    col_content = picker("content column", "content")
    col_format = picker("format column (optional)", "format")
    col_created_at = picker("created_at column (optional)", "created_at")
    col_meeting_id = picker("meeting_id column (optional)", "meeting_id")

    # Validate required mappings
    missing = []
    for label, colname in [
        ("parent_object", col_parent_object),
        ("parent_record_id", col_parent_record_id),
        ("title", col_title),
        ("content", col_content),
    ]:
        if colname == "(none)":
            missing.append(label)

    if missing:
        st.error(f"Missing required mappings: {', '.join(missing)}")
        st.stop()

    # Limit rows if requested
    work_df = df.copy()
    if max_rows and max_rows > 0:
        work_df = work_df.head(int(max_rows))

    st.write(f"**Rows to process:** {len(work_df)}")

    if dry_run:
        st.info("Dry run enabled: no API calls will be made.")
        # Show a preview of the built payload for the first few rows
        preview_count = min(3, len(work_df))
        st.subheader("Payload Preview (first few rows)")
        for i in range(preview_count):
            row = work_df.iloc[i]
            payload = build_note_payload(
                parent_object=row[col_parent_object],
                parent_record_id=row[col_parent_record_id],
                title=row[col_title],
                content=row[col_content],
                content_format_default=default_format,
                format_col_val=None if col_format == "(none)" else safe_iso(row[col_format]),
                created_at=None if col_created_at == "(none)" else safe_iso(row[col_created_at]),
                meeting_id=None if col_meeting_id == "(none)" else safe_iso(row[col_meeting_id]),
            )
            st.code(json.dumps(payload, indent=2))
        st.success("Looks good? Uncheck 'Dry run' to create notes.")
    else:
        if not token:
            st.error("Please provide an Attio API token in the sidebar.")
            st.stop()

        session = make_session(token)
        progress = st.progress(0)
        results = []
        total = len(work_df)

        for idx, (_, row) in enumerate(work_df.iterrows(), start=1):
            payload = build_note_payload(
                parent_object=row[col_parent_object],
                parent_record_id=row[col_parent_record_id],
                title=row[col_title],
                content=row[col_content],
                content_format_default=default_format,
                format_col_val=None if col_format == "(none)" else safe_iso(row[col_format]),
                created_at=None if col_created_at == "(none)" else safe_iso(row[col_created_at]),
                meeting_id=None if col_meeting_id == "(none)" else safe_iso(row[col_meeting_id]),
            )

            try:
                resp = post_with_retry(session, payload, max_retries=5)
                ok = 200 <= resp.status_code < 300
                info = resp.json() if resp.content else {}
                results.append({
                    "row": idx,
                    "status_code": resp.status_code,
                    "success": ok,
                    "note_id": info.get("data", {}).get("id", {}).get("note_id"),
                    "error": None if ok else info
                })
            except Exception as e:
                results.append({
                    "row": idx,
                    "status_code": None,
                    "success": False,
                    "note_id": None,
                    "error": str(e)
                })

            progress.progress(idx / total)

        st.subheader("Results")
        res_df = pd.DataFrame(results)
        st.dataframe(res_df)

        success_count = int(res_df["success"].sum())
        fail_count = int((~res_df["success"]).sum())
        st.write(f"✅ Success: **{success_count}** | ❌ Failed: **{fail_count}**")

        if fail_count > 0:
            st.warning("Some rows failed. Expand errors above and fix the inputs or try again.")