import requests
from requests_ntlm import HttpNtlmAuth
from .config import Config

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def _auth():
    return HttpNtlmAuth(
        f"{Config.SSRS_DOMAIN}\\{Config.SSRS_USER}",
        Config.SSRS_PASS
    )

def get_folders():
    try:
        resp = requests.get(
            f"{Config.SSRS_API}/Folders",
            auth=_auth(), timeout=10, verify=False
        )
        resp.raise_for_status()
        folders = resp.json().get("value", [])
        return [
            {
                "id": f.get("Id"),
                "name": f.get("Name"),
                "path": f.get("Path", ""),
            }
            for f in folders
            if f.get("Name") and not f.get("Hidden", False)
        ]
    except Exception as e:
        print(f"SSRS get_folders error: {e}")
        return []

def get_folder_reports(folder_path: str):
    try:
        auth = _auth()
        folder = folder_path.lstrip("/")
        url = f"{Config.SSRS_API}/Reports?$filter=startswith(Path,'/{folder}/')"
        resp = requests.get(url, auth=auth, timeout=15, verify=False)
        resp.raise_for_status()
        items = resp.json().get("value", [])
        if not items:
            items = _folder_catalog_items(folder_path, auth)
        return [
            {
                "id": r.get("Id", ""),
                "name": r.get("Name", ""),
                "path": r.get("Path", ""),
                "description": r.get("Description", "") or "",
                "modified": r.get("ModifiedDate", ""),
            }
            for r in items
            if r.get("Type", r.get("type", "")) in ("Report", "")
               and r.get("Name")
        ]
    except Exception as e:
        print(f"SSRS get_folder_reports error: {e}")
        return []

def _folder_catalog_items(folder_path: str, auth) -> list:
    try:
        resp = requests.get(f"{Config.SSRS_API}/Folders", auth=auth, timeout=10, verify=False)
        folders = resp.json().get("value", [])
        folder_id = None
        for f in folders:
            if f.get("Path", "").lower() == folder_path.lower() \
            or f.get("Name", "").lower() == folder_path.strip("/").lower():
                folder_id = f.get("Id")
                break
        if not folder_id:
            return []
        url = f"{Config.SSRS_API}/Folders({folder_id})/CatalogItems"
        resp = requests.get(url, auth=auth, timeout=15, verify=False)
        return resp.json().get("value", [])
    except:
        return []

def get_report_params(report_id: str):
    try:
        url = f"{Config.SSRS_API}/Reports({report_id})/ParameterDefinitions"
        resp = requests.get(url, auth=_auth(), timeout=10, verify=False)
        resp.raise_for_status()
        params = resp.json().get("value", [])
        return [
            {
                "name": p.get("Name"),
                "prompt": p.get("Prompt") or p.get("Name"),
                "type": p.get("ParameterTypeName", "String"),
                "nullable": p.get("Nullable", False),
                "allowBlank": p.get("AllowBlank", False),
                "multiValue": p.get("MultiValue", False),
                "validValues": [
                    
                    {"label": v.get("Label", v.get("Value")), "value": v.get("Value")}
                    for v in (
                        p.get("ValidValues") or [])
                ]
            }
            for p in params
            if not p.get("Hidden", False)
        ]
    except Exception as e:
        print(f"SSRS get_report_params error: {e}")
        return []

def stream_report(report_path: str, fmt: str, extra_params: dict):
    ext_map = {
        "PDF": ("pdf", "application/pdf"),
        "EXCELOPENXML": ("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
        "CSV": ("csv", "text/csv"),
        "WORD": ("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
    }
    fmt = fmt.upper()
    if fmt not in ext_map:
        fmt = "PDF"
    ext, content_type = ext_map[fmt]

    qs = "".join(f"&{k}={v}" for k, v in extra_params.items() if v)
    url = (
        f"{Config.SSRS_BASE}/ReportServer?{report_path}"
        f"&rs:Command=Render&rs:Format={fmt}{qs}"
    )
    try:
        resp = requests.get(
            url, auth=_auth(), timeout=120, verify=False, stream=True
        )
        return resp, ext, content_type
    except Exception as e:
        print(f"SSRS stream_report error: {e}")
        return None, ext, content_type