import json
from datetime import datetime
from decimal import Decimal

import requests
from flask import current_app
from flask_login import current_user
from sqlalchemy import or_, func

from .. import db
from ..models import (
    User, EmployeeProfile, Lead, LeadActivity, LeadStatus, LeadService,
    Opportunity, PipelineStage, Quote, QuoteItem, QuoteStatus, Client, ClientBranch,
    ProformaInvoice, Invoice,
)


SYSTEM_PROMPT = """You are CN Sales AI, a read-only sales assistant inside Crystal Nexus.

Security and scope rules:
1. You may use ONLY the sales tools provided to you. You do not have access to Finance, vendor commercial data, payroll, HR documents, bank data, tax IDs, credentials, or Tally data.
2. Never claim to have retrieved data that a tool did not return.
3. Respect the records returned by tools; they are already permission-scoped for the signed-in user.
4. If a user asks for restricted/non-sales information, say that CN Sales AI is intentionally limited to Sales data.
5. Do not expose email addresses, phone numbers, PAN/GST details, bank information, passwords, API keys, or other secrets. The tools deliberately omit these fields.
6. Be concise and practical. For lists, include identifiers such as lead code, opportunity code, or quote code so the user can locate the record in Crystal Nexus.
7. Monetary values are sales quotation/opportunity values only. Never infer collections, invoice payment, vendor cost, or profitability.
8. If the question is ambiguous, use the available search/overview tools and explain what you found.
9. You may give sales strategy, pitch ideas, objection-handling suggestions, and recommended next actions ONLY from the Crystal Nexus sales history returned by tools. Clearly distinguish stored facts from your recommendations. Do not pretend to know external facts about a client unless a tool returned them.
10. When asked how to close or pitch a client, prefer the client_sales_profile tool and structure the answer as: What CN knows, Buying signals/history, Recommended pitch angle, Suggested next steps, and Risks/questions to validate.
11. Make long record lists easy to scan. If a result contains 6 or more records, prefer a compact Markdown table instead of long bullet lines. Use short human-readable dates such as 19 Aug 2026, 05:30 PM. Keep columns focused on what the user asked for.
12. If a tool returns total_count and returned_count, state both only when they differ. Do not claim a partial list is complete.
13. You may report how many Proforma Invoices (PI) and client Invoices were generated for a requested date range for the signed-in user's permitted Sales scope. This is document-count Sales reporting only; do not discuss payments, collections, outstanding amounts, profitability, or vendor costs.

You can summarize leads, follow-ups, opportunities, pipeline, quotes, client sales history, client profiles, sales activity, and permission-scoped PI/invoice generation counts. You are read-only and cannot create or update Crystal Nexus records.
"""


def _decimal(v):
    if v is None:
        return 0.0
    if isinstance(v, Decimal):
        return float(v)
    try:
        return float(v)
    except Exception:
        return 0.0


def _dt(v):
    return v.isoformat() if v else None


def _team_user_ids(manager_user_id):
    seen = set()
    stack = [manager_user_id]
    while stack:
        manager_id = stack.pop()
        rows = (
            EmployeeProfile.query
            .filter(EmployeeProfile.reporting_manager_user_id == manager_id)
            .with_entities(EmployeeProfile.user_id)
            .all()
        )
        for row in rows:
            uid = row[0]
            if uid is not None and uid not in seen:
                seen.add(uid)
                stack.append(uid)
    return list(seen)


def _allowed_owner_ids():
    # Reuse the existing Sales visibility rule: leads.view_all = all users,
    # otherwise only self + nested reportees.
    if current_user.has_perm("leads.view_all"):
        return None
    return [current_user.id] + _team_user_ids(current_user.id)


def _scope_owner(query, column):
    allowed = _allowed_owner_ids()
    if allowed is not None:
        query = query.filter(column.in_(allowed))
    return query


def _search_leads(args):
    query_text = (args.get("query") or "").strip()
    status = (args.get("status") or "").strip()
    limit = min(max(int(args.get("limit") or 15), 1), 25)

    q = Lead.query
    q = _scope_owner(q, Lead.owner_id)
    if query_text:
        token = "%{}%".format(query_text)
        q = q.filter(or_(Lead.lead_code.ilike(token), Lead.name.ilike(token), Lead.company.ilike(token)))
    if status:
        q = q.join(LeadStatus, Lead.status_id == LeadStatus.id).filter(LeadStatus.name.ilike("%{}%".format(status)))

    rows = q.order_by(Lead.updated_at.desc()).limit(limit).all()
    return {
        "count": len(rows),
        "leads": [
            {
                "lead_code": r.lead_code,
                "contact_name": r.name,
                "company": r.company or (r.client.company_name if r.client else None),
                "branch": r.branch.branch_location if r.branch else None,
                "status": r.status.name if r.status else None,
                "source": r.source.name if r.source else None,
                "service": r.service.name if r.service else None,
                "owner": r.owner.name if r.owner else None,
                "estimated_closure_date": _dt(r.estimated_closure_date),
                "notes": (r.notes or "")[:600],
                "updated_at": _dt(r.updated_at),
            }
            for r in rows
        ],
    }


def _get_lead(args):
    code = (args.get("lead_code") or "").strip()
    q = Lead.query.filter(func.lower(Lead.lead_code) == code.lower())
    q = _scope_owner(q, Lead.owner_id)
    lead = q.first()
    if not lead:
        return {"found": False, "message": "Lead not found or not accessible."}

    activities = (
        LeadActivity.query.filter_by(lead_id=lead.id)
        .order_by(LeadActivity.activity_at.desc())
        .limit(12).all()
    )
    opps = Opportunity.query.filter_by(lead_id=lead.id)
    opps = _scope_owner(opps, Opportunity.owner_id).order_by(Opportunity.updated_at.desc()).all()
    return {
        "found": True,
        "lead": {
            "lead_code": lead.lead_code,
            "contact_name": lead.name,
            "company": lead.company or (lead.client.company_name if lead.client else None),
            "branch": lead.branch.branch_location if lead.branch else None,
            "status": lead.status.name if lead.status else None,
            "source": lead.source.name if lead.source else None,
            "service": lead.service.name if lead.service else None,
            "owner": lead.owner.name if lead.owner else None,
            "estimated_closure_date": _dt(lead.estimated_closure_date),
            "notes": (lead.notes or "")[:1000],
            "created_at": _dt(lead.created_at),
            "updated_at": _dt(lead.updated_at),
        },
        "recent_activities": [
            {
                "type": a.activity_type.name if a.activity_type else None,
                "subject": a.subject,
                "outcome": a.outcome,
                "notes": (a.notes or "")[:700],
                "activity_at": _dt(a.activity_at),
                "next_follow_up_at": _dt(a.next_follow_up_at),
                "created_by": a.created_by.name if a.created_by else None,
            }
            for a in activities
        ],
        "opportunities": [
            {
                "opp_code": o.opp_code,
                "title": o.title,
                "stage": o.stage.name if o.stage else None,
                "expected_value": _decimal(o.expected_value),
                "expected_close_date": _dt(o.expected_close_date),
                "owner": o.owner.name if o.owner else None,
            }
            for o in opps
        ],
    }


def _followups(args):
    timing = (args.get("timing") or "upcoming").lower()
    # Allow a complete, still-bounded list for requests such as "list all 53 overdue follow-ups".
    limit = min(max(int(args.get("limit") or 50), 1), 100)
    now = datetime.now()
    start = datetime.combine(now.date(), datetime.min.time())
    end = datetime.combine(now.date(), datetime.max.time())

    q = LeadActivity.query.join(Lead, LeadActivity.lead_id == Lead.id).filter(LeadActivity.next_follow_up_at.isnot(None))
    q = _scope_owner(q, Lead.owner_id)
    if timing == "overdue":
        q = q.filter(LeadActivity.next_follow_up_at < now)
    elif timing == "today":
        q = q.filter(LeadActivity.next_follow_up_at >= start, LeadActivity.next_follow_up_at <= end)
    else:
        q = q.filter(LeadActivity.next_follow_up_at >= now)

    total_count = q.count()
    rows = q.order_by(LeadActivity.next_follow_up_at.asc()).limit(limit).all()
    return {
        "timing": timing,
        "total_count": int(total_count or 0),
        "returned_count": len(rows),
        "followups": [
            {
                "lead_code": a.lead.lead_code if a.lead else None,
                "company": (a.lead.company or (a.lead.client.company_name if a.lead and a.lead.client else None)) if a.lead else None,
                "lead_status": a.lead.status.name if a.lead and a.lead.status else None,
                "owner": a.lead.owner.name if a.lead and a.lead.owner else None,
                "subject": a.subject,
                "outcome": a.outcome,
                "next_follow_up_at": _dt(a.next_follow_up_at),
                "last_activity_at": _dt(a.activity_at),
            }
            for a in rows
        ],
    }


def _search_opportunities(args):
    query_text = (args.get("query") or "").strip()
    stage = (args.get("stage") or "").strip()
    limit = min(max(int(args.get("limit") or 15), 1), 25)
    q = Opportunity.query
    q = _scope_owner(q, Opportunity.owner_id)
    if query_text:
        token = "%{}%".format(query_text)
        q = q.filter(or_(Opportunity.opp_code.ilike(token), Opportunity.title.ilike(token), Opportunity.company.ilike(token)))
    if stage:
        q = q.join(PipelineStage, Opportunity.stage_id == PipelineStage.id).filter(PipelineStage.name.ilike("%{}%".format(stage)))
    rows = q.order_by(Opportunity.updated_at.desc()).limit(limit).all()
    return {
        "count": len(rows),
        "opportunities": [
            {
                "opp_code": o.opp_code,
                "title": o.title,
                "company": o.company or (o.client.company_name if o.client else None),
                "branch": o.branch.branch_location if o.branch else None,
                "stage": o.stage.name if o.stage else None,
                "probability": o.stage.probability if o.stage else None,
                "expected_value": _decimal(o.expected_value),
                "expected_close_date": _dt(o.expected_close_date),
                "owner": o.owner.name if o.owner else None,
                "notes": (o.notes or "")[:700],
                "updated_at": _dt(o.updated_at),
            }
            for o in rows
        ],
    }


def _search_quotes(args):
    query_text = (args.get("query") or "").strip()
    status = (args.get("status") or "").strip()
    limit = min(max(int(args.get("limit") or 15), 1), 25)
    q = Quote.query.join(Opportunity, Quote.opportunity_id == Opportunity.id)
    q = _scope_owner(q, Opportunity.owner_id)
    if query_text:
        token = "%{}%".format(query_text)
        q = q.filter(or_(Quote.quote_code.ilike(token), Opportunity.opp_code.ilike(token), Opportunity.title.ilike(token), Opportunity.company.ilike(token)))
    if status:
        q = q.join(QuoteStatus, Quote.status_id == QuoteStatus.id).filter(QuoteStatus.name.ilike("%{}%".format(status)))
    rows = q.order_by(Quote.id.desc()).limit(limit).all()
    result = []
    for r in rows:
        items = r.items.order_by(QuoteItem.sort_order.asc(), QuoteItem.id.asc()).limit(20).all()
        result.append({
            "quote_code": r.quote_code,
            "version": r.version,
            "status": r.status.name if r.status else None,
            "opportunity_code": r.opportunity.opp_code if r.opportunity else None,
            "opportunity": r.opportunity.title if r.opportunity else None,
            "company": (r.client.company_name if r.client else (r.opportunity.company if r.opportunity else None)),
            "owner": r.opportunity.owner.name if r.opportunity and r.opportunity.owner else None,
            "currency": r.currency,
            "subtotal": _decimal(r.subtotal),
            "discount": _decimal(r.discount),
            "total": _decimal(r.total),
            "valid_until": _dt(r.valid_until),
            "estimated_closure_date": _dt(r.estimated_closure_date),
            "items": [
                {
                    "service": i.service.name if i.service else None,
                    "item": i.item_name,
                    "qty": _decimal(i.qty),
                    "rate": _decimal(i.rate),
                    "amount": _decimal(i.amount),
                    "billing_cycle": i.billing_cycle,
                }
                for i in items
            ],
        })
    return {"count": len(result), "quotes": result}


def _client_sales_history(args):
    query_text = (args.get("query") or "").strip()
    if not query_text:
        return {"found": False, "message": "Please provide a client/company name."}
    token = "%{}%".format(query_text)
    allowed = _allowed_owner_ids()

    opp_q = Opportunity.query.filter(or_(Opportunity.company.ilike(token), Opportunity.client.has(Client.company_name.ilike(token))))
    if allowed is not None:
        opp_q = opp_q.filter(Opportunity.owner_id.in_(allowed))
    opps = opp_q.order_by(Opportunity.updated_at.desc()).limit(25).all()
    if not opps:
        return {"found": False, "message": "No accessible sales history found for that client."}

    opp_ids = [o.id for o in opps]
    quotes = Quote.query.filter(Quote.opportunity_id.in_(opp_ids)).order_by(Quote.id.desc()).limit(30).all()
    return {
        "found": True,
        "opportunities": [
            {
                "opp_code": o.opp_code,
                "title": o.title,
                "company": o.company or (o.client.company_name if o.client else None),
                "stage": o.stage.name if o.stage else None,
                "expected_value": _decimal(o.expected_value),
                "expected_close_date": _dt(o.expected_close_date),
                "owner": o.owner.name if o.owner else None,
            }
            for o in opps
        ],
        "quotes": [
            {
                "quote_code": q.quote_code,
                "status": q.status.name if q.status else None,
                "currency": q.currency,
                "total": _decimal(q.total),
                "valid_until": _dt(q.valid_until),
                "opportunity_code": q.opportunity.opp_code if q.opportunity else None,
            }
            for q in quotes
        ],
    }


def _client_sales_profile(args):
    query_text = (args.get("query") or "").strip()
    if not query_text:
        return {"found": False, "message": "Please provide a client/company name."}

    token = "%{}%".format(query_text)
    allowed = _allowed_owner_ids()

    # A client is visible to the assistant only when the signed-in user can see
    # sales records linked to it. Users with leads.view_all can use the full
    # client master; everyone else remains restricted to self/reportee sales data.
    client_q = Client.query.filter(Client.company_name.ilike(token))
    if allowed is not None:
        accessible_client_ids = set()
        for row in (
            Opportunity.query
            .filter(Opportunity.owner_id.in_(allowed), Opportunity.client_id.isnot(None))
            .with_entities(Opportunity.client_id).distinct().all()
        ):
            if row[0] is not None:
                accessible_client_ids.add(row[0])
        for row in (
            Lead.query
            .filter(Lead.owner_id.in_(allowed), Lead.client_id.isnot(None))
            .with_entities(Lead.client_id).distinct().all()
        ):
            if row[0] is not None:
                accessible_client_ids.add(row[0])
        if not accessible_client_ids:
            return {"found": False, "message": "No accessible client sales profile found."}
        client_q = client_q.filter(Client.id.in_(list(accessible_client_ids)))

    clients = client_q.order_by(Client.company_name.asc()).limit(5).all()

    # Also support prospect/company text that may not yet be mapped to Client master.
    if not clients:
        opp_q = Opportunity.query.filter(Opportunity.company.ilike(token))
        lead_q = Lead.query.filter(Lead.company.ilike(token))
        if allowed is not None:
            opp_q = opp_q.filter(Opportunity.owner_id.in_(allowed))
            lead_q = lead_q.filter(Lead.owner_id.in_(allowed))
        opps = opp_q.order_by(Opportunity.updated_at.desc()).limit(20).all()
        leads = lead_q.order_by(Lead.updated_at.desc()).limit(20).all()
        if not opps and not leads:
            return {"found": False, "message": "No accessible client or prospect sales history found."}
        return {
            "found": True,
            "client_master_match": False,
            "company": query_text,
            "message": "This company is present in accessible sales records but did not match the Client Master.",
            "leads": [
                {
                    "lead_code": l.lead_code,
                    "status": l.status.name if l.status else None,
                    "service": l.service.name if l.service else None,
                    "owner": l.owner.name if l.owner else None,
                    "estimated_closure_date": _dt(l.estimated_closure_date),
                    "notes": (l.notes or "")[:500],
                    "updated_at": _dt(l.updated_at),
                } for l in leads
            ],
            "opportunities": [
                {
                    "opp_code": o.opp_code,
                    "title": o.title,
                    "stage": o.stage.name if o.stage else None,
                    "probability": o.stage.probability if o.stage else None,
                    "expected_value": _decimal(o.expected_value),
                    "expected_close_date": _dt(o.expected_close_date),
                    "owner": o.owner.name if o.owner else None,
                    "notes": (o.notes or "")[:500],
                } for o in opps
            ],
        }

    profiles = []
    for client in clients:
        opp_q = Opportunity.query.filter(Opportunity.client_id == client.id)
        lead_q = Lead.query.filter(Lead.client_id == client.id)
        if allowed is not None:
            opp_q = opp_q.filter(Opportunity.owner_id.in_(allowed))
            lead_q = lead_q.filter(Lead.owner_id.in_(allowed))
        opps = opp_q.order_by(Opportunity.updated_at.desc()).limit(25).all()
        leads = lead_q.order_by(Lead.updated_at.desc()).limit(25).all()
        opp_ids = [o.id for o in opps]
        quotes = Quote.query.filter(Quote.opportunity_id.in_(opp_ids)).order_by(Quote.id.desc()).limit(40).all() if opp_ids else []

        quote_status_counts = {}
        service_totals = {}
        quoted_total_by_currency = {}
        for q in quotes:
            st = q.status.name if q.status else "Unknown"
            quote_status_counts[st] = quote_status_counts.get(st, 0) + 1
            curr = q.currency or "INR"
            quoted_total_by_currency[curr] = quoted_total_by_currency.get(curr, 0.0) + _decimal(q.total)
            for item in q.items.order_by(QuoteItem.sort_order.asc(), QuoteItem.id.asc()).limit(40).all():
                svc = item.service.name if item.service else (item.item_name or "Other")
                service_totals[svc] = service_totals.get(svc, 0.0) + _decimal(item.amount)

        recent_activities = []
        lead_ids = [l.id for l in leads]
        if lead_ids:
            acts = (LeadActivity.query.filter(LeadActivity.lead_id.in_(lead_ids))
                    .order_by(LeadActivity.activity_at.desc()).limit(12).all())
            recent_activities = [
                {
                    "lead_code": a.lead.lead_code if a.lead else None,
                    "type": a.activity_type.name if a.activity_type else None,
                    "subject": a.subject,
                    "outcome": a.outcome,
                    "notes": (a.notes or "")[:450],
                    "activity_at": _dt(a.activity_at),
                    "next_follow_up_at": _dt(a.next_follow_up_at),
                } for a in acts
            ]

        branches = []
        for b in client.branches.filter_by(is_active=True).order_by(ClientBranch.branch_location.asc()).limit(20).all():
            branches.append({
                "branch": b.branch_location,
                "city": b.city,
                "state": b.state_master.name if b.state_master else b.state,
                "country": b.country_master.name if b.country_master else b.country,
            })

        profiles.append({
            "company_name": client.company_name,
            "industry": client.industry.name if client.industry else client.company_industry,
            "client_type": client.client_type,
            "client_category": client.client_category,
            "service_profile": client.service,
            "active": bool(client.is_active),
            "branches": branches,
            "sales_summary": {
                "lead_count": len(leads),
                "opportunity_count": len(opps),
                "quote_count": len(quotes),
                "quote_status_counts": quote_status_counts,
                "quoted_total_by_currency": quoted_total_by_currency,
                "top_quoted_services_by_value": [
                    {"service": k, "quoted_value": v}
                    for k, v in sorted(service_totals.items(), key=lambda kv: kv[1], reverse=True)[:8]
                ],
            },
            "recent_leads": [
                {
                    "lead_code": l.lead_code,
                    "status": l.status.name if l.status else None,
                    "service": l.service.name if l.service else None,
                    "owner": l.owner.name if l.owner else None,
                    "estimated_closure_date": _dt(l.estimated_closure_date),
                    "notes": (l.notes or "")[:500],
                    "updated_at": _dt(l.updated_at),
                } for l in leads[:10]
            ],
            "recent_opportunities": [
                {
                    "opp_code": o.opp_code,
                    "title": o.title,
                    "stage": o.stage.name if o.stage else None,
                    "probability": o.stage.probability if o.stage else None,
                    "expected_value": _decimal(o.expected_value),
                    "expected_close_date": _dt(o.expected_close_date),
                    "owner": o.owner.name if o.owner else None,
                    "notes": (o.notes or "")[:500],
                } for o in opps[:12]
            ],
            "recent_quotes": [
                {
                    "quote_code": q.quote_code,
                    "status": q.status.name if q.status else None,
                    "currency": q.currency,
                    "total": _decimal(q.total),
                    "valid_until": _dt(q.valid_until),
                    "estimated_closure_date": _dt(q.estimated_closure_date),
                } for q in quotes[:12]
            ],
            "recent_activities": recent_activities,
        })

    return {"found": True, "client_master_match": True, "matches": len(profiles), "clients": profiles}




def _parse_date_arg(value, field_name):
    value = (value or "").strip()
    if not value:
        return None
    try:
        return datetime.strptime(value, "%Y-%m-%d").date()
    except Exception:
        raise ValueError("{} must be YYYY-MM-DD.".format(field_name))


def _sales_document_counts(args):
    """
    Permission-scoped Sales reporting only.
    Counts actual PI / client invoice documents linked through Quote -> Opportunity owner.
    No payment, collection, vendor, profitability or bank data is exposed.
    """
    from_date = _parse_date_arg(args.get("from_date"), "from_date")
    to_date = _parse_date_arg(args.get("to_date"), "to_date")
    if not from_date or not to_date:
        return {"error": "Please provide both from_date and to_date in YYYY-MM-DD format."}
    if from_date > to_date:
        return {"error": "from_date cannot be after to_date."}

    scope = (args.get("scope") or "team").strip().lower()
    if scope not in ("me", "team"):
        scope = "team"

    if scope == "me":
        owner_ids = [current_user.id]
    else:
        allowed = _allowed_owner_ids()
        # A user with leads.view_all can see all Sales owners; otherwise team visibility applies.
        owner_ids = allowed

    pi_q = (
        ProformaInvoice.query
        .join(Quote, ProformaInvoice.quote_id == Quote.id)
        .join(Opportunity, Quote.opportunity_id == Opportunity.id)
        .filter(ProformaInvoice.pi_date >= from_date, ProformaInvoice.pi_date <= to_date)
    )
    inv_q = (
        Invoice.query
        .join(Quote, Invoice.quote_id == Quote.id)
        .join(Opportunity, Quote.opportunity_id == Opportunity.id)
        .filter(Invoice.invoice_date >= from_date, Invoice.invoice_date <= to_date)
    )

    if owner_ids is not None:
        pi_q = pi_q.filter(Opportunity.owner_id.in_(owner_ids))
        inv_q = inv_q.filter(Opportunity.owner_id.in_(owner_ids))

    # Exclude cancelled documents from the generated counts.
    pi_q = pi_q.filter(or_(ProformaInvoice.is_cancelled.is_(False), ProformaInvoice.is_cancelled.is_(None)))
    inv_q = inv_q.filter(or_(Invoice.is_cancelled.is_(False), Invoice.is_cancelled.is_(None)))

    pi_rows = pi_q.with_entities(
        ProformaInvoice.id, ProformaInvoice.pi_no, ProformaInvoice.pi_date,
        Opportunity.owner_id
    ).order_by(ProformaInvoice.pi_date.asc(), ProformaInvoice.id.asc()).all()

    inv_rows = inv_q.with_entities(
        Invoice.id, Invoice.invoice_no, Invoice.invoice_date,
        Opportunity.owner_id
    ).order_by(Invoice.invoice_date.asc(), Invoice.id.asc()).all()

    user_ids = set([r[3] for r in pi_rows] + [r[3] for r in inv_rows])
    user_names = {}
    if user_ids:
        for uid, name in User.query.filter(User.id.in_(list(user_ids))).with_entities(User.id, User.name).all():
            user_names[uid] = name or "User {}".format(uid)

    by_owner = {}
    for row in pi_rows:
        owner_id = row[3]
        bucket = by_owner.setdefault(owner_id, {"owner": user_names.get(owner_id, "Unknown"), "pi_count": 0, "invoice_count": 0})
        bucket["pi_count"] += 1
    for row in inv_rows:
        owner_id = row[3]
        bucket = by_owner.setdefault(owner_id, {"owner": user_names.get(owner_id, "Unknown"), "pi_count": 0, "invoice_count": 0})
        bucket["invoice_count"] += 1

    breakdown = sorted(by_owner.values(), key=lambda x: (-x["invoice_count"], -x["pi_count"], x["owner"]))

    return {
        "from_date": from_date.isoformat(),
        "to_date": to_date.isoformat(),
        "scope": scope,
        "pi_count": len(pi_rows),
        "invoice_count": len(inv_rows),
        "by_owner": breakdown,
        "pi_documents": [
            {"pi_no": r[1], "pi_date": _dt(r[2]), "owner": user_names.get(r[3], "Unknown")}
            for r in pi_rows[:100]
        ],
        "invoice_documents": [
            {"invoice_no": r[1], "invoice_date": _dt(r[2]), "owner": user_names.get(r[3], "Unknown")}
            for r in inv_rows[:100]
        ],
        "note": "Counts are actual non-cancelled documents linked to Sales owners through Quote -> Opportunity. No payment or collection data is included."
    }


def _sales_overview(args):
    allowed = _allowed_owner_ids()
    lead_q = Lead.query
    opp_q = Opportunity.query
    if allowed is not None:
        lead_q = lead_q.filter(Lead.owner_id.in_(allowed))
        opp_q = opp_q.filter(Opportunity.owner_id.in_(allowed))

    lead_statuses = (
        db_group(LeadStatus.name, func.count(Lead.id), Lead, LeadStatus, Lead.status_id == LeadStatus.id, Lead.owner_id, allowed)
    )
    opp_stages = (
        db_group(PipelineStage.name, func.count(Opportunity.id), Opportunity, PipelineStage, Opportunity.stage_id == PipelineStage.id, Opportunity.owner_id, allowed)
    )

    now = datetime.now()
    follow_q = LeadActivity.query.join(Lead, LeadActivity.lead_id == Lead.id).filter(LeadActivity.next_follow_up_at.isnot(None))
    if allowed is not None:
        follow_q = follow_q.filter(Lead.owner_id.in_(allowed))

    return {
        "total_leads": lead_q.count(),
        "lead_statuses": lead_statuses,
        "total_opportunities": opp_q.count(),
        "opportunity_stages": opp_stages,
        "pipeline_expected_value": _decimal(opp_q.with_entities(func.coalesce(func.sum(Opportunity.expected_value), 0)).scalar()),
        "overdue_followups": follow_q.filter(LeadActivity.next_follow_up_at < now).count(),
        "upcoming_followups": follow_q.filter(LeadActivity.next_follow_up_at >= now).count(),
    }


def db_group(label_col, count_col, base_model, join_model, join_condition, owner_col, allowed):
    q = base_model.query.join(join_model, join_condition).with_entities(label_col, count_col).group_by(label_col)
    if allowed is not None:
        q = q.filter(owner_col.in_(allowed))
    return [{"name": r[0] or "Unknown", "count": int(r[1] or 0)} for r in q.all()]


TOOL_DISPATCH = {
    "sales_overview": _sales_overview,
    "search_leads": _search_leads,
    "get_lead": _get_lead,
    "list_followups": _followups,
    "search_opportunities": _search_opportunities,
    "search_quotes": _search_quotes,
    "client_sales_history": _client_sales_history,
    "client_sales_profile": _client_sales_profile,
    "sales_document_counts": _sales_document_counts,
}

TOOLS = [
    {"type": "function", "function": {"name": "sales_overview", "description": "Get a permission-scoped sales overview: lead counts, pipeline counts/value, and follow-up counts.", "parameters": {"type": "object", "properties": {}, "additionalProperties": False}}},
    {"type": "function", "function": {"name": "search_leads", "description": "Search accessible leads by lead code, contact/company text, and optional lead status.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "status": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 25}}, "additionalProperties": False}}},
    {"type": "function", "function": {"name": "get_lead", "description": "Get one accessible lead with recent sales activities and linked opportunities.", "parameters": {"type": "object", "properties": {"lead_code": {"type": "string"}}, "required": ["lead_code"], "additionalProperties": False}}},
    {"type": "function", "function": {"name": "list_followups", "description": "List accessible sales follow-ups. timing can be overdue, today, or upcoming. Use a sufficiently large limit when the user asks for all records.", "parameters": {"type": "object", "properties": {"timing": {"type": "string", "enum": ["overdue", "today", "upcoming"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}}, "additionalProperties": False}}},
    {"type": "function", "function": {"name": "search_opportunities", "description": "Search accessible opportunities by opportunity code/title/company and optional pipeline stage.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "stage": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 25}}, "additionalProperties": False}}},
    {"type": "function", "function": {"name": "search_quotes", "description": "Search accessible sales quotations and their line items. Contains quotation sales values only, not invoice/payment/vendor data.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "status": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 25}}, "additionalProperties": False}}},
    {"type": "function", "function": {"name": "client_sales_history", "description": "Get accessible opportunity and quotation history for a client/company. Sales history only.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"], "additionalProperties": False}}},
    {"type": "function", "function": {"name": "sales_document_counts", "description": "Count actual non-cancelled Proforma Invoices (PI) and client Invoices generated in a specific date range for the signed-in user's permitted Sales scope. Can show 'me' or 'team' and owner-wise counts. This is Sales document-count reporting only; it does not expose payments, collections, outstanding amounts, vendor data or profitability.", "parameters": {"type": "object", "properties": {"from_date": {"type": "string", "description": "Start date in YYYY-MM-DD format"}, "to_date": {"type": "string", "description": "End date in YYYY-MM-DD format"}, "scope": {"type": "string", "enum": ["me", "team"]}}, "required": ["from_date", "to_date"], "additionalProperties": False}}},
    {"type": "function", "function": {"name": "client_sales_profile", "description": "Get a permission-scoped client/prospect sales profile for pitching and closure guidance. Includes non-sensitive Client Master context, branches/geography, leads, opportunities, quote status/value trends, quoted services, and recent sales activities. Use this when asked about a client, how to pitch them, how to close them, buying history, or recommended next steps.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"], "additionalProperties": False}}},
]


def ask_sales_ai(history_messages):
    api_key = (current_app.config.get("OPENAI_API_KEY") or "").strip()
    if not api_key:
        raise RuntimeError("OPENAI_API_KEY is not configured on the server.")

    api_url = current_app.config.get("OPENAI_API_URL") or "https://api.openai.com/v1/chat/completions"
    model = current_app.config.get("OPENAI_MODEL") or "gpt-5-mini"
    timeout = int(current_app.config.get("OPENAI_TIMEOUT") or 60)

    # Only user/assistant text history is sent. Crystal Nexus DB data is sent only
    # when the model calls one of the permission-scoped sales tools above.
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    for msg in history_messages[-12:]:
        if msg.role in ("user", "assistant"):
            messages.append({"role": msg.role, "content": (msg.content or "")[:12000]})

    headers = {"Authorization": "Bearer {}".format(api_key), "Content-Type": "application/json"}
    last_usage = {}
    for _ in range(5):
        payload = {"model": model, "messages": messages, "tools": TOOLS, "tool_choice": "auto"}
        response = requests.post(api_url, headers=headers, json=payload, timeout=timeout)
        if response.status_code >= 400:
            detail = response.text[:1000]
            raise RuntimeError("OpenAI API error {}: {}".format(response.status_code, detail))
        data = response.json()
        last_usage = data.get("usage") or {}
        choices = data.get("choices") or []
        if not choices:
            raise RuntimeError("OpenAI API returned no response choice.")
        message = choices[0].get("message") or {}
        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            return (message.get("content") or "I could not produce a response."), last_usage

        messages.append(message)
        for call in tool_calls:
            fn = (call.get("function") or {}).get("name")
            raw_args = (call.get("function") or {}).get("arguments") or "{}"
            try:
                args = json.loads(raw_args)
            except Exception:
                args = {}
            handler = TOOL_DISPATCH.get(fn)
            if not handler:
                tool_result = {"error": "Tool is not available."}
            else:
                try:
                    tool_result = handler(args)
                except Exception as exc:
                    current_app.logger.exception("CN Sales AI tool failed: %s", fn)
                    tool_result = {"error": "The Crystal Nexus sales query could not be completed."}
            messages.append({
                "role": "tool",
                "tool_call_id": call.get("id"),
                "content": json.dumps(tool_result, default=str),
            })

    raise RuntimeError("The AI assistant used too many tool steps. Please try a more specific question.")
