import os
from datetime import datetime
from rich.console import Console
from rich.prompt import Confirm

console = Console()

try:
    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    from reportlab.lib import colors
    from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.graphics import renderPDF
    from svglib.svglib import svg2rlg
    HAS_REPORTLAB = True
except ImportError:
    HAS_REPORTLAB = False

def check_auth_and_generate_pdf(report_data, output_path=os.path.join(os.path.dirname(os.path.dirname(__file__)), "reports", "SentinelX_Report.pdf")):
    if not HAS_REPORTLAB:
        console.print("[bold red]Error: reportlab or svglib is not installed.[/bold red]")
        return

    console.print("[bold yellow]PDF Generation Request[/bold yellow]")
    if not Confirm.ask("Do you have explicit authorization to generate this report for the target system?"):
        console.print("[bold red]Aborted: Authorization declined.[/bold red]")
        return

    # Ensure reports dir exists
    os.makedirs(os.path.join(os.path.dirname(os.path.dirname(__file__)), "reports"), exist_ok=True)
    
    doc = SimpleDocTemplate(output_path, pagesize=letter, topMargin=40)
    styles = getSampleStyleSheet()
    story = []

    # 1. SVG Logo
    logo_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "assets", "logo.svg")
    if os.path.exists(logo_path):
        try:
            drawing = svg2rlg(logo_path)
            # Scale logo to fit nicely (e.g. 80% width of page or fixed width)
            # Drawing width is ~600 in SVG. Let us scale it down to ~400 points width.
            scaling_factor = 400.0 / drawing.width
            drawing.width = drawing.width * scaling_factor
            drawing.height = drawing.height * scaling_factor
            drawing.scale(scaling_factor, scaling_factor)
            story.append(drawing)
            story.append(Spacer(1, 24))
        except Exception as e:
            console.print(f"[red]Warning: Could not render SVG logo: {e}[/red]")
            story.append(Paragraph("SENTINELX", styles["Title"]))
    else:
        story.append(Paragraph("SENTINELX", styles["Title"]))

    # 2. Title & Date
    title_style = styles["Title"]
    story.append(Paragraph("Security Assessment Report", title_style))
    story.append(Spacer(1, 12))
    
    date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    normal_style = styles["Normal"]
    story.append(Paragraph(f"<b>Generated:</b> {date_str}", normal_style))
    story.append(Spacer(1, 24))

    # 3. Operations Performed Section
    h2_style = styles["Heading2"]
    story.append(Paragraph("Operations Performed", h2_style))
    story.append(Spacer(1, 6))
    
    # Description text
    op_text = "The following operations were executed by the SentinelX framework under authorized conditions. " \
              "This report details the modules used, targets scanned, and preliminary findings."
    story.append(Paragraph(op_text, normal_style))
    story.append(Spacer(1, 12))

    # 4. Data Table
    if report_data:
        # Convert dict to list of lists for table
        data = [["Parameter", "Details"]]
        for k, v in report_data.items():
            # Wrap long values
            data.append([str(k), Paragraph(str(v), normal_style)])
            
        t = Table(data, colWidths=[150, 300])
        t.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#111111")), # Dark Header
            ("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
            ("FONTSIZE", (0, 0), (-1, 0), 12),
            ("BOTTOMPADDING", (0, 0), (-1, 0), 12),
            ("TOPPADDING", (0, 0), (-1, 0), 12),
            ("BACKGROUND", (0, 1), (-1, -1), colors.whitesmoke),
            ("GRID", (0, 0), (-1, -1), 1, colors.grey),
            ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ]))
        story.append(t)
    
    # Footer Disclaimer
    story.append(Spacer(1, 40))
    disclaimer_style = ParagraphStyle("Disclaimer", parent=styles["Normal"], textColor=colors.red, fontSize=8, alignment=1)
    story.append(Paragraph("CONFIDENTIAL: Authorized Personnel Only. Generated by SentinelX v2.2", disclaimer_style))

    doc.build(story)
    console.print(f"[bold green]✔ PDF Report generated at: {output_path}[/bold green]")

if __name__ == "__main__":
    dummy_data = {
        "Target System": "192.168.1.105", 
        "Scan Type": "Red Team / Reconnaissance",
        "Modules Executed": "Nmap, Nikto",
        "Status": "Completed",
        "Notes": "Open ports found: 22, 80, 443. Web server identifies as Apache 2.4."
    }
    check_auth_and_generate_pdf(dummy_data)
