import os
import sys
from datetime import datetime
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.graphics.shapes import Drawing, Circle, String
import arabic_reshaper
from bidi.algorithm import get_display

from database import db
from utils.date_utils import to_shamsi

def reshape_text(text: str) -> str:
    if not text:
        return ""
    # Shape Arabic/Persian letters
    reshaped = arabic_reshaper.reshape(text)
    # Reorder LTR representation to RTL display order
    bidi_text = get_display(reshaped)
    return bidi_text

def get_system_seal() -> Drawing:
    """Generates a beautiful vector seal for the invoice."""
    d = Drawing(120, 120)
    # Background circular border
    d.add(Circle(60, 60, 50, strokeColor=colors.HexColor("#2B6CB0"), strokeWidth=2, fillColor=colors.HexColor("#EBF8FF")))
    d.add(Circle(60, 60, 46, strokeColor=colors.HexColor("#2B6CB0"), strokeWidth=1, fillColor=None))
    
    # Text inside seal
    d.add(String(60, 80, reshape_text("ایکس‌لنسر"), fontName="Tahoma-Bold", fontSize=10, textAnchor="middle", fillColor=colors.HexColor("#1A365D")))
    d.add(String(60, 60, reshape_text("پرداخت امن"), fontName="Tahoma", fontSize=9, textAnchor="middle", fillColor=colors.HexColor("#2B6CB0")))
    d.add(String(60, 40, reshape_text("تایید سیستمی"), fontName="Tahoma", fontSize=8, textAnchor="middle", fillColor=colors.HexColor("#48BB78")))
    
    return d

async def generate_farsi_invoice_pdf(
    project_id: int,
    project_title: str,
    client_id: int,
    client_name: str,
    freelancer_id: int,
    freelancer_name: str,
    amount: int,
    commission: int,
    payout: int,
    commission_pct: int,
    milestone_title: str = None,
    milestone_id: int = None,
    is_refund: bool = False,
    promo_discount: int = 0,
) -> str:
    """
    Generates a beautiful Farsi PDF invoice / refund receipt / dispute split document
    using ReportLab and Tahoma font. Returns the file path.
    """
    # 1. Register Tahoma font (safe path in Windows)
    tahoma_path = "C:\\Windows\\Fonts\\tahoma.ttf"
    tahoma_bold_path = "C:\\Windows\\Fonts\\tahomabd.ttf"
    try:
        pdfmetrics.registerFont(TTFont('Tahoma', tahoma_path))
        pdfmetrics.registerFont(TTFont('Tahoma-Bold', tahoma_bold_path))
    except Exception as e:
        print(f"Warning: Failed to register Tahoma font: {e}. Falling back to default fonts.")
        # Fallback to Helvetica if Tahoma is not found (though Tahoma is guaranteed on Windows)
        pdfmetrics.registerFont(TTFont('Tahoma', 'Helvetica'))
        pdfmetrics.registerFont(TTFont('Tahoma-Bold', 'Helvetica-Bold'))

    # Output path
    pdf_dir = "invoices"
    os.makedirs(pdf_dir, exist_ok=True)
    suffix = "refund" if is_refund else "invoice"
    pdf_path = os.path.join(pdf_dir, f"invoice_{project_id}_{suffix}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf")
    
    # Doc template setup (A4 size with margins)
    doc = SimpleDocTemplate(pdf_path, pagesize=A4, rightMargin=40, leftMargin=40, topMargin=40, bottomMargin=40)
    story = []
    
    # Styles
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'InvoiceTitle',
        parent=styles['Heading1'],
        fontName='Tahoma-Bold',
        fontSize=18,
        alignment=1, # Center
        textColor=colors.HexColor("#1A365D"),
        spaceAfter=5
    )
    subtitle_style = ParagraphStyle(
        'InvoiceSubtitle',
        parent=styles['Normal'],
        fontName='Tahoma',
        fontSize=9,
        alignment=1, # Center
        textColor=colors.HexColor("#718096"),
        spaceAfter=15
    )
    normal_style = ParagraphStyle(
        'InvoiceNormal',
        parent=styles['Normal'],
        fontName='Tahoma',
        fontSize=9,
        alignment=2, # Right for Persian
        textColor=colors.HexColor("#2D3748"),
        leading=14
    )
    bold_style = ParagraphStyle(
        'InvoiceBold',
        parent=styles['Normal'],
        fontName='Tahoma-Bold',
        fontSize=9,
        alignment=2, # Right
        textColor=colors.HexColor("#1A365D"),
        leading=14
    )
    
    # Header
    header_title = "رسید رسمی استرداد وجه پرداخت امن" if is_refund else "فاکتور رسمی پرداخت امن سیستمی"
    story.append(Paragraph(reshape_text(f"ایکس‌لنسر - {header_title}"), title_style))
    story.append(Paragraph(reshape_text("سامانه هوشمند و تسهیل‌گر فریلنسینگ تلگرام"), subtitle_style))
    
    # Divider line
    divider = Table([[""]], colWidths=[515])
    divider.setStyle(TableStyle([
        ('LINEBELOW', (0,0), (-1,-1), 1.5, colors.HexColor("#3182CE")),
        ('BOTTOMPADDING', (0,0), (-1,-1), 0),
        ('TOPPADDING', (0,0), (-1,-1), 0),
    ]))
    story.append(divider)
    story.append(Spacer(1, 15))
    
    # Meta Info Block (RTL Layout)
    now_shamsi = to_shamsi(datetime.now())
    inv_number = f"INV-{project_id}-{datetime.now().strftime('%m%d%H%M')}"
    
    info_data = [
        [
            reshape_text(now_shamsi), reshape_text("تاریخ صدور:"),
            reshape_text(client_name), reshape_text("کارفرما:")
        ],
        [
            reshape_text(inv_number), reshape_text("شماره فاکتور:"),
            reshape_text(freelancer_name if freelancer_id else "ندارد"), reshape_text("فریلنسر:")
        ],
        [
            reshape_text(f"#{project_id}"), reshape_text("شناسه پروژه:"),
            reshape_text(project_title[:30]), reshape_text("عنوان پروژه:")
        ]
    ]
    info_table = Table(info_data, colWidths=[150, 80, 200, 85], hAlign='RIGHT')
    info_table.setStyle(TableStyle([
        ('FONTNAME', (0,0), (-1,-1), 'Tahoma'),
        ('FONTSIZE', (0,0), (-1,-1), 9),
        ('ALIGN', (0,0), (-1,-1), 'RIGHT'),
        ('TEXTCOLOR', (0,0), (0,-1), colors.HexColor("#2D3748")),
        ('TEXTCOLOR', (1,0), (1,-1), colors.HexColor("#718096")),
        ('TEXTCOLOR', (2,0), (2,-1), colors.HexColor("#2D3748")),
        ('TEXTCOLOR', (3,0), (3,-1), colors.HexColor("#718096")),
        ('BOTTOMPADDING', (0,0), (-1,-1), 6),
        ('FONTNAME', (1,0), (1,-1), 'Tahoma-Bold'),
        ('FONTNAME', (3,0), (3,-1), 'Tahoma-Bold'),
    ]))
    story.append(info_table)
    story.append(Spacer(1, 20))
    
    # Financial breakdown details
    # Description determination
    if is_refund:
        desc_str = f"استرداد کامل وجه پروژه #{project_id} به کارفرما"
    elif milestone_title:
        desc_str = f"آزادسازی فاز «{milestone_title}» پروژه #{project_id}"
    else:
        # Check if it was a split dispute settlement
        refund_amount = amount - payout - commission
        if refund_amount > 0 and payout > 0:
            desc_str = f"تسویه پروژه #{project_id} بر اساس تقسیم سهم داوری"
        else:
            desc_str = f"تسویه نهایی و کامل پروژه #{project_id}"

    table_headers = [
        reshape_text("مبلغ خالص نهایی (تومان)"),
        reshape_text("سهم کمیسیون پلتفرم"),
        reshape_text("مجموع کل سپرده امانی"),
        reshape_text("شرح تراکنش مالی"),
        reshape_text("ردیف")
    ]
    
    # Formatted strings for table
    escrow_str = f"{amount:,}"
    commission_str = f"{commission:,}"
    
    refund_amount = amount - payout - commission
    if is_refund:
        payout_str = f"استرداد: {amount:,}"
    elif refund_amount > 0 and payout > 0:
        payout_str = f"فریلنسر: {payout:,}\nکارفرما: {refund_amount:,}"
    else:
        payout_str = f"{payout:,}"
        
    row_data = [
        reshape_text(payout_str),
        reshape_text(commission_str),
        reshape_text(escrow_str),
        reshape_text(desc_str),
        reshape_text("۱")
    ]
    
    financial_data = [table_headers, row_data]
    financial_table = Table(financial_data, colWidths=[130, 95, 95, 170, 25], hAlign='CENTER')
    financial_table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.HexColor("#1A365D")),
        ('TEXTCOLOR', (0,0), (-1,0), colors.white),
        ('FONTNAME', (0,0), (-1,-1), 'Tahoma'),
        ('FONTSIZE', (0,0), (-1,-1), 9),
        ('ALIGN', (0,0), (-1,-1), 'CENTER'),
        ('BOTTOMPADDING', (0,0), (-1,-1), 10),
        ('TOPPADDING', (0,0), (-1,-1), 10),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
    ]))
    story.append(financial_table)
    story.append(Spacer(1, 40))
    
    # Seal & Footer Section (Two column layout: Sign/Seal on left, Terms on right)
    terms_table = Table([
        [reshape_text("توضیحات و قوانین پرداخت امن سیستمی:")],
        [reshape_text("۱. این فاکتور الکترونیکی صادر شده و دارای اعتبار رسمی و سیستمی است.")],
        [reshape_text("۲. تراکنش‌های مالی این سند از طریق درگاه پرداخت ربات تایید شده است.")],
        [reshape_text("۳. هرگونه اختلاف مالی توسط هیئت داوران ایکس‌لنسر بررسی و نهایی شده است.")]
    ], colWidths=[395], hAlign='RIGHT')
    terms_table.setStyle(TableStyle([
        ('FONTNAME', (0,0), (-1,-1), 'Tahoma'),
        ('FONTSIZE', (0,0), (-1,-1), 8),
        ('ALIGN', (0,0), (-1,-1), 'RIGHT'),
        ('TEXTCOLOR', (0,0), (-1,-1), colors.HexColor("#2D3748")),
        ('FONTNAME', (0,0), (0,0), 'Tahoma-Bold'),
        ('FONTSIZE', (0,0), (0,0), 9),
        ('TEXTCOLOR', (0,0), (0,0), colors.HexColor("#1A365D")),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))

    footer_data = [
        [
            get_system_seal(),
            terms_table
        ]
    ]
    
    footer_table = Table(footer_data, colWidths=[120, 395], hAlign='CENTER')
    footer_table.setStyle(TableStyle([
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('ALIGN', (0,0), (0,0), 'LEFT'),
        ('ALIGN', (1,0), (1,0), 'RIGHT'),
    ]))
    story.append(footer_table)
    
    # Build Document
    doc.build(story)
    return pdf_path

async def create_project_invoice(project_id: int) -> str:
    """
    Fetches details for project_id, generates a beautiful Farsi PDF invoice,
    saves it to invoices/invoice_{project_id}.pdf, and returns the file path.
    """
    # Fetch project, client, freelancer, transactions info
    project = await db.get_project(project_id)
    if not project:
        raise ValueError(f"Project #{project_id} not found")
        
    project = dict(project)
    client = await db.get_user(project['client_id'])
    freelancer = await db.get_user(project['chosen_freelancer_id']) if project['chosen_freelancer_id'] else None
    
    txs = await db.get_project_transactions(project_id)
    
    client_name = client['full_name'] or client['username'] or str(project['client_id']) if client else "نامشخص"
    freelancer_name = freelancer['full_name'] or freelancer['username'] or str(project['chosen_freelancer_id']) if freelancer else "نامشخص"
    
    # Calculate values from transactions
    escrow_amount = 0
    commission_amount = 0
    payout_amount = 0
    refund_amount = 0
    
    # Check escrow table directly
    import aiosqlite
    from config import DB_PATH
    async with aiosqlite.connect(DB_PATH) as conn:
        conn.row_factory = aiosqlite.Row
        async with conn.execute('SELECT amount FROM escrow WHERE project_id = ?', (project_id,)) as cursor:
            row = await cursor.fetchone()
            if row:
                escrow_amount = row['amount']
                
    for t in txs:
        if t['tx_type'] == 'earning':
            payout_amount += t['amount']
        elif t['tx_type'] == 'commission':
            commission_amount += abs(t['amount'])
        elif t['tx_type'] == 'refund':
            refund_amount += t['amount']
            
    # Default fallback calculation if transaction history is empty
    if escrow_amount == 0 and payout_amount == 0:
        escrow_amount = project['budget_max']
        
    if payout_amount == 0 and refund_amount == 0:
        commission_amount = int(escrow_amount * 0.10)
        payout_amount = escrow_amount - commission_amount
        
    is_refund = (refund_amount > 0 and payout_amount == 0)
    
    # Calculate commission percentage
    commission_pct = 0
    if escrow_amount > 0:
        commission_pct = int((commission_amount / escrow_amount) * 100)
    elif payout_amount > 0:
        commission_pct = int((commission_amount / (payout_amount + commission_amount)) * 100)
        
    return await generate_farsi_invoice_pdf(
        project_id=project_id,
        project_title=project['title'],
        client_id=project['client_id'],
        client_name=client_name,
        freelancer_id=project['chosen_freelancer_id'] or 0,
        freelancer_name=freelancer_name,
        amount=escrow_amount if escrow_amount > 0 else (payout_amount + refund_amount),
        commission=commission_amount,
        payout=payout_amount,
        commission_pct=commission_pct,
        is_refund=is_refund,
    )
