#!/usr/bin/env python3
# relatorio_feegow.py
# Uso: python3 relatorio_feegow.py manha   (relatório das 12h)
#      python3 relatorio_feegow.py tarde    (relatório das 18h)

import sys
import json
import smtplib
import requests
from datetime import datetime, timedelta, timezone
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# ── CONFIG ───────────────────────────────────────────────────
CONFIG_FILE = '/home/ubuntu/feegow_config.json'

with open(CONFIG_FILE) as f:
    cfg = json.load(f)

FEEGOW_TOKEN = cfg['feegow_token']
SMTP_USER    = cfg['smtp_user']
SMTP_PASS    = cfg['smtp_pass']
EMAIL_TO     = cfg['email_to']

BASE_URL = 'https://api.feegow.com/v1/api'
HEADERS  = {'x-access-token': FEEGOW_TOKEN}

# ── HELPERS ──────────────────────────────────────────────────
def feegow(path):
    r = requests.get(BASE_URL + path, headers=HEADERS, timeout=30)
    r.raise_for_status()
    data = r.json()
    if data.get('success') is False:
        raise Exception(f'Feegow error: {data}')
    return data.get('content') or []

def brl(v):
    return f'R$ {v:,.2f}'.replace(',', 'X').replace('.', ',').replace('X', '.')

def pct(v, total):
    return f'{v/total*100:.1f}%' if total > 0 else '–'

def api_date(iso):   # YYYY-MM-DD → DD-MM-YYYY
    return iso.split('-')[::-1]and '-'.join(iso.split('-')[::-1])

BRT      = timezone(timedelta(hours=-3))
hoje     = datetime.now(BRT)

MESES = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho',
         'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro']

def mes_nome_br(dt):
    return f'{MESES[dt.month-1]}/{dt.year}'
hoje_str = hoje.strftime('%d-%m-%Y')
hoje_iso = hoje.strftime('%Y-%m-%d')
ontem    = (hoje - timedelta(days=1))
ontem_str= ontem.strftime('%d-%m-%Y')
mes_ini  = hoje.replace(day=1).strftime('%d-%m-%Y')
mes_ini_iso = hoje.replace(day=1).strftime('%Y-%m-%d')

STATUS = {
    1:'Marcado',3:'Atendido',6:'Faltou',7:'Confirmado',
    11:'Cancelado paciente',15:'Remarcado',16:'Cancelado clínica',
}

# ── CORES / ESTILO ───────────────────────────────────────────
CSS = """
<style>
  body{font-family:'Segoe UI',Arial,sans-serif;background:#f0f2f8;margin:0;padding:20px;}
  .wrap{max-width:620px;margin:0 auto;}
  .header{background:linear-gradient(135deg,#0d1b4b,#1a237e);color:#fff;border-radius:12px 12px 0 0;
          padding:20px 24px;}
  .header h1{margin:0;font-size:1.15rem;}
  .header p{margin:4px 0 0;font-size:.8rem;opacity:.7;}
  .body{background:#fff;padding:20px 24px;border-radius:0 0 12px 12px;
        box-shadow:0 4px 16px rgba(0,0,0,.1);}
  .section{margin-bottom:20px;}
  .section-title{font-size:.7rem;text-transform:uppercase;letter-spacing:.8px;
                 color:#888;font-weight:700;margin-bottom:10px;border-bottom:2px solid #eee;
                 padding-bottom:6px;}
  .kpi-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:16px;}
  .kpi{background:#f4f5fb;border-radius:8px;padding:12px 14px;border-left:3px solid #1a237e;}
  .kpi.green{border-color:#43a047;background:#f1f8e9;}
  .kpi.red{border-color:#c62828;background:#fff3f3;}
  .kpi.orange{border-color:#ff8a65;background:#fff8f4;}
  .kpi-val{font-size:1.1rem;font-weight:800;color:#1a237e;}
  .kpi-val.green{color:#2e7d32;}
  .kpi-val.red{color:#c62828;}
  .kpi-lbl{font-size:.65rem;color:#999;text-transform:uppercase;letter-spacing:.5px;margin-top:2px;}
  table{width:100%;border-collapse:collapse;font-size:.82rem;}
  th{font-size:.65rem;text-transform:uppercase;color:#888;padding:6px 8px;
     border-bottom:2px solid #eee;text-align:left;font-weight:600;}
  td{padding:7px 8px;border-bottom:1px solid #f4f4f4;color:#333;}
  tr:last-child td{border-bottom:none;}
  .tag{display:inline-block;padding:2px 8px;border-radius:10px;font-size:.7rem;font-weight:600;}
  .tag-green{background:#e8f5e9;color:#2e7d32;}
  .tag-red{background:#ffebee;color:#c62828;}
  .tag-orange{background:#fff3e0;color:#e65100;}
  .tag-gray{background:#f5f5f5;color:#666;}
  .alert{border-radius:8px;padding:10px 14px;margin-bottom:8px;font-size:.83rem;}
  .alert-red{background:#ffebee;border-left:3px solid #c62828;color:#7f0000;}
  .alert-yellow{background:#fffde7;border-left:3px solid #f9a825;color:#6d4c00;}
  .alert-green{background:#f1f8e9;border-left:3px solid #43a047;color:#1b5e20;}
  .footer{font-size:.72rem;color:#aaa;text-align:center;margin-top:16px;}
</style>
"""

# ── RELATÓRIO DA MANHÃ (12h) ─────────────────────────────────
def relatorio_manha():
    print('Buscando agendamentos do dia...')
    apts = feegow(f'/appoints/search?data_start={hoje_str}&data_end={hoje_str}')

    total   = len(apts)
    atend   = sum(1 for a in apts if a.get('status_id') == 3)
    confirm = sum(1 for a in apts if a.get('status_id') == 7)
    cancel  = sum(1 for a in apts if a.get('status_id') in (11, 15, 16))
    pendente= total - atend - cancel

    # Agrupar por profissional
    by_prof = {}
    for a in apts:
        pid = a.get('profissional_id', 0)
        nome = a.get('profissional_nome') or a.get('profissional') or f'ID {pid}'
        if pid not in by_prof:
            by_prof[pid] = {'nome': nome, 'total': 0, 'atend': 0}
        by_prof[pid]['total'] += 1
        if a.get('status_id') == 3:
            by_prof[pid]['atend'] += 1

    profs_sorted = sorted(by_prof.values(), key=lambda x: -x['total'])

    # Próximos agendamentos (pendentes, por horário)
    proximos = sorted(
        [a for a in apts if a.get('status_id') not in (11, 15, 16, 3)],
        key=lambda x: x.get('horario', '')
    )[:10]

    rows_profs = ''
    for p in profs_sorted:
        rows_profs += f"""
        <tr>
          <td>{p['nome']}</td>
          <td style="text-align:center">{p['total']}</td>
          <td style="text-align:center">{p['atend']}</td>
          <td style="text-align:center">{pct(p['atend'], p['total'])}</td>
        </tr>"""

    rows_prox = ''
    for a in proximos:
        st = a.get('status_id', 0)
        tag_cls = 'tag-green' if st == 7 else ('tag-orange' if st == 1 else 'tag-gray')
        tag_txt = STATUS.get(st, f'Status {st}')
        rows_prox += f"""
        <tr>
          <td>{a.get('horario','–')[:5]}</td>
          <td>{a.get('paciente_nome') or a.get('paciente','–')}</td>
          <td>{a.get('profissional_nome') or a.get('profissional','–')}</td>
          <td><span class="tag {tag_cls}">{tag_txt}</span></td>
        </tr>"""

    html = f"""{CSS}
<div class="wrap">
  <div class="header">
    <h1>📅 Agenda do dia — {hoje_str}</h1>
    <p>Relatório gerado às {datetime.now().strftime('%H:%M')} · Feegow Dashboard</p>
  </div>
  <div class="body">

    <div class="section">
      <div class="section-title">Resumo</div>
      <div class="kpi-grid">
        <div class="kpi"><div class="kpi-val">{total}</div><div class="kpi-lbl">Total agendados</div></div>
        <div class="kpi green"><div class="kpi-val green">{atend}</div><div class="kpi-lbl">Atendidos até agora</div></div>
        <div class="kpi orange"><div class="kpi-val orange">{pendente}</div><div class="kpi-lbl">Pendentes</div></div>
        <div class="kpi green"><div class="kpi-val green">{confirm}</div><div class="kpi-lbl">Confirmados</div></div>
        <div class="kpi red"><div class="kpi-val red">{cancel}</div><div class="kpi-lbl">Cancelados</div></div>
        <div class="kpi"><div class="kpi-val">{pct(atend, total)}</div><div class="kpi-lbl">Taxa comparec.</div></div>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Por profissional</div>
      <table>
        <tr><th>Profissional</th><th style="text-align:center">Total</th>
            <th style="text-align:center">Atend.</th><th style="text-align:center">%</th></tr>
        {rows_profs}
      </table>
    </div>

    <div class="section">
      <div class="section-title">Próximos agendamentos</div>
      <table>
        <tr><th>Horário</th><th>Paciente</th><th>Profissional</th><th>Status</th></tr>
        {rows_prox if rows_prox else '<tr><td colspan="4" style="color:#bbb;padding:12px">Sem próximos agendamentos</td></tr>'}
      </table>
    </div>

    <div class="footer">
      Feegow Dashboard · {hoje_str} · <a href="https://dmtrindade.duckdns.org/dashboard.html">Abrir dashboard</a>
    </div>
  </div>
</div>"""

    return f'📅 Agenda de hoje — {hoje_str} ({total} agendamentos)', html


# ── RELATÓRIO DA TARDE (18h) ─────────────────────────────────
def relatorio_tarde():
    import calendar as cal
    print('Buscando dados financeiros...')

    # Período do mês anterior (mesmo dia)
    if hoje.month == 1:
        prev_year, prev_month = hoje.year - 1, 12
    else:
        prev_year, prev_month = hoje.year, hoje.month - 1
    prev_last_day   = cal.monthrange(prev_year, prev_month)[1]
    mes_ant_ini_str = datetime(prev_year, prev_month, 1).strftime('%d-%m-%Y')
    mes_ant_fim_str = datetime(prev_year, prev_month, min(hoje.day, prev_last_day)).strftime('%d-%m-%Y')
    mes_ant_nome    = mes_nome_br(datetime(prev_year, prev_month, 1))

    invoices_hoje    = feegow(f'/financial/list-invoice?data_start={hoje_str}&data_end={hoje_str}&tipo_transacao=C')
    invoices_mes     = feegow(f'/financial/list-invoice?data_start={mes_ini}&data_end={hoje_str}&tipo_transacao=C')
    expenses_mes     = feegow(f'/financial/list-invoice?data_start={mes_ini}&data_end={hoje_str}&tipo_transacao=D')
    invoices_mes_ant = feegow(f'/financial/list-invoice?data_start={mes_ant_ini_str}&data_end={mes_ant_fim_str}&tipo_transacao=C')

    def sum_inv(lst):
        return sum((x.get('detalhes') or [{}])[0].get('valor', 0) / 100 for x in lst
                   if x.get('pagamentos') and x['pagamentos'][0].get('forma_pagamento') is not None)

    def sum_exp(lst):
        return sum((x.get('detalhes') or [{}])[0].get('valor', 0) / 100 for x in lst)

    fat_hoje    = sum_inv(invoices_hoje)
    fat_mes     = sum_inv(invoices_mes)
    desp_mes    = sum_exp(expenses_mes)
    fat_mes_ant = sum_inv(invoices_mes_ant)
    resultado   = fat_mes - desp_mes

    var_pct = ((fat_mes - fat_mes_ant) / fat_mes_ant * 100) if fat_mes_ant > 0 else 0
    var_sinal = '+' if var_pct >= 0 else ''
    var_txt = f'{var_sinal}{var_pct:.1f}%'
    var_cls = 'green' if var_pct >= 0 else 'red'
    res_cls = 'green' if resultado >= 0 else 'red'
    mes_nome = mes_nome_br(hoje)

    html = f"""{CSS}
<div class="wrap">
  <div class="header">
    <h1>💰 Fechamento do dia — {hoje_str}</h1>
    <p>Relatório gerado às {hoje.strftime('%H:%M')} · Feegow Dashboard</p>
  </div>
  <div class="body">

    <div class="section">
      <div class="section-title">Faturamento de hoje</div>
      <div class="kpi-grid" style="grid-template-columns:1fr;">
        <div class="kpi">
          <div class="kpi-val">{brl(fat_hoje)}</div>
          <div class="kpi-lbl">Receita — {hoje_str}</div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Mês atual — Faturamento acumulado</div>
      <div class="kpi-grid" style="grid-template-columns:1fr 1fr 1fr;">
        <div class="kpi">
          <div class="kpi-val">{brl(fat_mes)}</div>
          <div class="kpi-lbl">{mes_nome}</div>
        </div>
        <div class="kpi">
          <div class="kpi-val">{brl(fat_mes_ant)}</div>
          <div class="kpi-lbl">{mes_ant_nome} (mesmo período)</div>
        </div>
        <div class="kpi {var_cls}">
          <div class="kpi-val {var_cls}">{var_txt}</div>
          <div class="kpi-lbl">Variação</div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Resultado Financeiro — {mes_nome}</div>
      <table>
        <tr>
          <td style="padding:10px 8px;color:#333;">Receita Bruta</td>
          <td style="text-align:right;padding:10px 8px;font-weight:700;">{brl(fat_mes)}</td>
        </tr>
        <tr>
          <td style="padding:10px 8px;color:#c62828;">(-) Despesas Totais</td>
          <td style="text-align:right;padding:10px 8px;font-weight:700;color:#c62828;">({brl(desp_mes)})</td>
        </tr>
        <tr style="border-top:2px solid #1a237e;background:#f4f5fb;">
          <td style="padding:12px 8px;font-weight:800;color:{'#2e7d32' if resultado >= 0 else '#c62828'};">(=) Resultado Líquido</td>
          <td style="text-align:right;padding:12px 8px;font-weight:800;font-size:1.1rem;color:{'#2e7d32' if resultado >= 0 else '#c62828'};">{brl(resultado)}</td>
        </tr>
      </table>
    </div>

    <div class="footer">
      Feegow Dashboard · {hoje_str} · <a href="https://dmtrindade.duckdns.org/dashboard.html">Abrir dashboard</a>
    </div>
  </div>
</div>"""

    emoji = '✅' if resultado >= 0 else '⚠️'
    return f'{emoji} Fechamento {hoje_str} — {brl(fat_hoje)} faturados', html


# ── ENVIAR EMAIL ─────────────────────────────────────────────
def send_email(subject, html_body):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From']    = SMTP_USER
    msg['To']      = EMAIL_TO
    msg.attach(MIMEText(html_body, 'html', 'utf-8'))

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(SMTP_USER, SMTP_PASS)
        smtp.sendmail(SMTP_USER, EMAIL_TO, msg.as_string())
    print(f'Email enviado: {subject}')


# ── MAIN ─────────────────────────────────────────────────────
if __name__ == '__main__':
    tipo = sys.argv[1] if len(sys.argv) > 1 else 'tarde'
    if tipo == 'manha':
        subject, body = relatorio_manha()
    else:
        subject, body = relatorio_tarde()
    send_email(subject, body)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
