from pathlib import Path
from PIL import Image, ImageDraw
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image as RLImage, Table, TableStyle, PageBreak, KeepTogether
from xml.sax.saxutils import escape

ROOT = Path(r'C:\xampp\htdocs\Sewing-Project')
OUT = ROOT / 'output'
PHOTO = Path(r'C:\Users\pc\Downloads\489957759_2108825472897761_2120124840722340973_n.jpg')
DOCX_PATH = OUT / 'Mohamed_Adham_Ismail_Photo_CV.docx'
PDF_DIR = OUT / 'pdf'
PDF_DIR.mkdir(parents=True, exist_ok=True)
PDF_PATH = PDF_DIR / 'Mohamed_Adham_Ismail_Photo_CV.pdf'
PIC = ROOT / 'tmp' / 'resume_portrait.png'

# Prepare a small, circular portrait crop for both editable Word and PDF.
src = Image.open(PHOTO).convert('RGB')
w, h = src.size
side = int(min(w, h) * .66)
# Use a close upper-body crop so the portrait reads clearly at resume size.
left = (w-side)//2
top = max(0, min(h-side, int((h-side)*0.08)))
src = src.crop((left, top, left+side, top+side)).resize((480,480), Image.Resampling.LANCZOS)
mask = Image.new('L', (480,480), 0)
ImageDraw.Draw(mask).ellipse((2,2,478,478), fill=255)
src.putalpha(mask)
src.save(PIC)

NAVY = (18,39,67)
BLUE = (0,125,213)
TEXT = (48,55,64)

def set_cell_margins(cell, top=60, start=70, bottom=40, end=70):
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    mar = OxmlElement('w:tcMar')
    for tag, val in [('top',top),('start',start),('bottom',bottom),('end',end)]:
        node = OxmlElement('w:'+tag); node.set(qn('w:w'), str(val)); node.set(qn('w:type'),'dxa'); mar.append(node)
    tcPr.append(mar)

def no_borders(table):
    tblPr = table._tbl.tblPr
    borders = OxmlElement('w:tblBorders')
    for edge in ('top','left','bottom','right','insideH','insideV'):
        tag=OxmlElement('w:'+edge); tag.set(qn('w:val'),'nil'); borders.append(tag)
    tblPr.append(borders)

def set_run(run, size=8.7, bold=False, color=TEXT):
    run.font.name='Arial'; run.font.size=Pt(size); run.bold=bold; run.font.color.rgb=RGBColor(*color)

def cell_text(cell, text, size=8.6, bold=False, color=TEXT, after=1, before=0):
    p = cell.add_paragraph() if cell.paragraphs[0].text else cell.paragraphs[0]
    p.paragraph_format.space_before=Pt(before); p.paragraph_format.space_after=Pt(after); p.paragraph_format.line_spacing=1.0
    set_run(p.add_run(text), size, bold, color)
    return p

def heading(cell, text):
    return cell_text(cell, text.upper(), 11, True, BLUE, after=3, before=6)

def subheading(cell, text):
    return cell_text(cell, text, 9.6, True, NAVY, after=0, before=3)

def bullet(cell, text):
    p=cell.add_paragraph(); p.paragraph_format.left_indent=Inches(.13); p.paragraph_format.first_line_indent=Inches(-.11); p.paragraph_format.space_after=Pt(1); p.paragraph_format.line_spacing=1.0
    set_run(p.add_run('• '+text),8.15,False,TEXT)
    return p

doc=Document(); sec=doc.sections[0]
sec.top_margin=Inches(.48); sec.bottom_margin=Inches(.48); sec.left_margin=Inches(.62); sec.right_margin=Inches(.62)
normal=doc.styles['Normal']; normal.font.name='Arial'; normal.font.size=Pt(8.5); normal.font.color.rgb=RGBColor(*TEXT); normal.paragraph_format.space_after=Pt(1)
doc.core_properties.title='Mohamed Adham Ismail - Photo Resume'; doc.core_properties.author='Mohamed Adham Ismail'

# Header: identity and contact details beside a circular portrait.
t=doc.add_table(rows=1, cols=2); t.alignment=WD_TABLE_ALIGNMENT.CENTER; t.autofit=False; no_borders(t)
t.columns[0].width=Inches(6.15); t.columns[1].width=Inches(1.0)
left,right=t.rows[0].cells; left.width=Inches(6.15); right.width=Inches(1.0)
for c in (left,right): set_cell_margins(c,top=0,start=0,bottom=30,end=0); c.vertical_alignment=WD_CELL_VERTICAL_ALIGNMENT.CENTER
p=left.paragraphs[0]; p.paragraph_format.space_after=Pt(0); set_run(p.add_run('MOHAMED ADHAM ISMAIL'),22,True,NAVY)
p=left.add_paragraph(); p.paragraph_format.space_after=Pt(4); set_run(p.add_run('Senior Full Stack Developer'),11,True,BLUE)
for s in ['Riyadh, Saudi Arabia  |  0543577633  |  mohamedadhamismail@gmail.com',
          'linkedin.com/in/mohamed-adham-313882240  |  github.com/mohamedadhamahmed']:
    p=left.add_paragraph(); p.paragraph_format.space_after=Pt(1); set_run(p.add_run(s),8.2,False,TEXT)
p=right.paragraphs[0]; p.alignment=WD_ALIGN_PARAGRAPH.RIGHT; p.add_run().add_picture(str(PIC), width=Inches(.95), height=Inches(.95))

body=doc.add_table(rows=1, cols=2); body.alignment=WD_TABLE_ALIGNMENT.CENTER; body.autofit=False; no_borders(body)
body.columns[0].width=Inches(4.55); body.columns[1].width=Inches(2.6)
main,side=body.rows[0].cells; main.width=Inches(4.55); side.width=Inches(2.6)
for c in (main,side): set_cell_margins(c,top=25,start=0,bottom=0,end=110)

heading(main,'Summary')
cell_text(main,'Senior Full Stack Developer with 5+ years of experience designing and delivering large-scale enterprise web and mobile applications. Specializes in PHP, Laravel, Flutter, and Dart, with experience building ERP platforms, logistics systems, RESTful APIs, and cross-platform mobile apps. Develops offline-first workflows that let users continue working without an internet connection and synchronize data when connectivity returns. Skilled in database design and optimization, Clean Architecture, application state management, cloud integrations, and end-to-end app delivery. Improved database query performance by 40% and mentored developers on SOLID principles and clean code.',8.05,False,TEXT,2)

heading(main,'Experience')
subheading(main,'Senior Full Stack Developer')
cell_text(main,'Ebdaa Soft for Software  |  2022 - Present',8.35,True,BLUE,after=1)
bullet(main,'Lead development of enterprise software solutions using Laravel and Vue.js.')
bullet(main,'Architect and maintain MySQL and PostgreSQL databases; optimize queries to improve performance by 40%.')
bullet(main,'Develop Flutter applications for internal management systems and integrate them with web backends.')
bullet(main,'Mentor junior developers and conduct code reviews, reinforcing SOLID principles and clean code standards.')
subheading(main,'Full Stack Developer')
cell_text(main,'NSAF (Logistics Tech)  |  2021 - 2022',8.35,True,BLUE,after=1)
bullet(main,'Developed a truck logistics platform with real-time bidding and order management.')
bullet(main,'Integrated Google Maps API for live tracking and route calculation for drivers across Saudi Arabia.')
bullet(main,'Implemented payment gateway integration and real-time notifications using Firebase Cloud Messaging.')
bullet(main,'Managed the application lifecycle from concept through deployment to Google Play and the App Store.')
subheading(main,'Flutter Developer')
cell_text(main,'MTI  |  2020 - 2021',8.35,True,BLUE,after=1)
bullet(main,'Developed and maintained mobile applications focused on responsive design and user experience.')
bullet(main,'Integrated RESTful APIs and managed application state using Bloc and GetX.')
subheading(main,'Freelance Flutter Developer')
cell_text(main,'Self-Employed  |  2018 - 2020',8.35,True,BLUE,after=1)
bullet(main,'Delivered custom mobile applications for clients, including e-commerce solutions.')

heading(side,'Skills')
for label,vals in [
 ('Backend','PHP, Laravel, RESTful API Design, MySQL, PostgreSQL, SQLite'),
 ('Mobile','Flutter, Dart, Bloc, GetX, Provider, Firebase, Firebase Cloud Messaging'),
 ('Frontend','JavaScript, Vue.js, HTML5, CSS3, Bootstrap, Tailwind CSS'),
 ('Architecture','Clean Architecture, MVC, MVVM, SOLID, Object-Oriented Programming (OOP)'),
 ('Tools and Platforms','Git, GitHub, Docker, Postman, Dio/HTTP, CI/CD, Google Maps API'),
 ('Offline Capabilities','Offline-First Applications, Local Workflows, Data Synchronization on Reconnection')]:
    cell_text(side,label,8.7,True,BLUE,after=1,before=3)
    cell_text(side,vals,8.0,False,TEXT,after=3)

doc.add_page_break()
page2=doc.add_table(rows=1, cols=2); page2.alignment=WD_TABLE_ALIGNMENT.CENTER; page2.autofit=False; no_borders(page2)
page2.columns[0].width=Inches(2.6); page2.columns[1].width=Inches(4.55)
edu,projects=page2.rows[0].cells; edu.width=Inches(2.6); projects.width=Inches(4.55)
for c in (edu,projects): set_cell_margins(c,top=20,start=0,bottom=0,end=110)
heading(edu,'Education')
subheading(edu,'Bachelor of Computer Science')
cell_text(edu,'Benha University, Faculty of Computers and Artificial Intelligence',8.4,True,BLUE,after=2)
cell_text(edu,'2016 - 2020',8.3,False,TEXT,after=2)
cell_text(edu,'Major: Computer Science',8.3,False,TEXT,after=1)
cell_text(edu,'GPA: 2.6 / 4.0',8.3,False,TEXT,after=3)
heading(edu,'Languages')
cell_text(edu,'Arabic: Native',8.5,False,TEXT,after=2)
cell_text(edu,'English: Very Good (Professional Working Proficiency)',8.5,False,TEXT,after=2)
heading(projects,'ERP Projects')
cell_text(projects,'Delivered ERP solutions for seven business sectors:',8.5,False,TEXT,after=3)
for title,desc in [
 ('Accounting ERP','ERP solution for accounting and financial operations.'),
 ('Manufacturing ERP','ERP solution for factory and manufacturing operations.'),
 ('Clinic Management ERP','ERP solution for clinic operations.'),
 ('Pharmacy ERP','ERP solution for pharmacy operations.'),
 ('Supermarket ERP and POS','Retail ERP and point-of-sale solution for supermarket operations.'),
 ('Automotive Spare Parts ERP','ERP solution for automotive spare parts business operations.'),
 ('Restaurant Management ERP','ERP solution for restaurant operations, including a Flutter-based interface.')]:
    subheading(projects,title); cell_text(projects,desc,8.3,False,TEXT,after=3)
doc.save(DOCX_PATH)

# Build a close-matching, searchable PDF version with the same two-column hierarchy.
navy=colors.HexColor('#122743'); blue=colors.HexColor('#007DD5'); text=colors.HexColor('#303740')
pdf=SimpleDocTemplate(str(PDF_PATH),pagesize=letter,leftMargin=.62*inch,rightMargin=.62*inch,topMargin=.48*inch,bottomMargin=.48*inch,
                      title='Mohamed Adham Ismail - Photo Resume',author='Mohamed Adham Ismail')
styles={
 'name':ParagraphStyle('name',fontName='Helvetica-Bold',fontSize=20,leading=22,textColor=navy,spaceAfter=1),
 'role':ParagraphStyle('role',fontName='Helvetica-Bold',fontSize=10.5,leading=12,textColor=blue,spaceAfter=4),
 'contact':ParagraphStyle('contact',fontName='Helvetica',fontSize=8,leading=10,textColor=text,spaceAfter=1),
 'head':ParagraphStyle('head',fontName='Helvetica-Bold',fontSize=10.7,leading=12,textColor=blue,spaceBefore=5,spaceAfter=3),
 'sub':ParagraphStyle('sub',fontName='Helvetica-Bold',fontSize=9,leading=10.5,textColor=navy,spaceBefore=3,spaceAfter=1,keepWithNext=True),
 'org':ParagraphStyle('org',fontName='Helvetica-Bold',fontSize=8.1,leading=9.5,textColor=blue,spaceAfter=1,keepWithNext=True),
 'body':ParagraphStyle('body',fontName='Helvetica',fontSize=7.75,leading=9.15,textColor=text,spaceAfter=2),
 'bullet':ParagraphStyle('bullet',fontName='Helvetica',fontSize=7.65,leading=9.0,textColor=text,leftIndent=9,firstLineIndent=-6,spaceAfter=1),
 'skill':ParagraphStyle('skill',fontName='Helvetica',fontSize=7.7,leading=9.1,textColor=text,spaceAfter=3),
}
def para(text,style): return Paragraph(text,styles[style])
header_left=[para('<b>MOHAMED ADHAM ISMAIL</b>','name'),para('Senior Full Stack Developer','role'),
 para('Riyadh, Saudi Arabia  |  0543577633  |  mohamedadhamismail@gmail.com','contact'),
 para('linkedin.com/in/mohamed-adham-313882240  |  github.com/mohamedadhamahmed','contact')]
portrait=RLImage(str(PIC),width=.95*inch,height=.95*inch)
header=Table([[header_left,portrait]],colWidths=[6.15*inch,1.0*inch])
header.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'MIDDLE'),('ALIGN',(1,0),(1,0),'RIGHT'),('LEFTPADDING',(0,0),(-1,-1),0),('RIGHTPADDING',(0,0),(-1,-1),0),('TOPPADDING',(0,0),(-1,-1),0),('BOTTOMPADDING',(0,0),(-1,-1),3)]))
leftcol=[para('SUMMARY','head'),para('Senior Full Stack Developer with 5+ years of experience designing and delivering large-scale enterprise web and mobile applications. Specializes in PHP, Laravel, Flutter, and Dart, with experience building ERP platforms, logistics systems, RESTful APIs, and cross-platform mobile apps. Develops offline-first workflows that let users continue working without an internet connection and synchronize data when connectivity returns. Skilled in database design and optimization, Clean Architecture, application state management, cloud integrations, and end-to-end app delivery. Improved database query performance by 40% and mentored developers on SOLID principles and clean code.','body'),
 para('EXPERIENCE','head')]
def addjob(title,org,dates,bullets):
    items=[para(escape(title),'sub'),para(f'{escape(org)}  |  {escape(dates)}','org')]
    items += [para('&bull;  '+escape(x),'bullet') for x in bullets]
    leftcol.extend(items)
addjob('Senior Full Stack Developer','Ebdaa Soft for Software','2022 - Present',[
 'Lead development of enterprise software solutions using Laravel and Vue.js.',
 'Architect and maintain MySQL and PostgreSQL databases; optimize queries to improve performance by 40%.',
 'Develop Flutter applications for internal management systems and integrate them with web backends.',
 'Mentor junior developers and conduct code reviews, reinforcing SOLID principles and clean code standards.'])
addjob('Full Stack Developer','NSAF (Logistics Tech)','2021 - 2022',[
 'Developed a truck logistics platform with real-time bidding and order management.',
 'Integrated Google Maps API for live tracking and route calculation for drivers across Saudi Arabia.',
 'Implemented payment gateway integration and real-time notifications using Firebase Cloud Messaging.',
 'Managed the application lifecycle from concept through deployment to Google Play and the App Store.'])
addjob('Flutter Developer','MTI','2020 - 2021',[
 'Developed and maintained mobile applications focused on responsive design and user experience.',
 'Integrated RESTful APIs and managed application state using Bloc and GetX.'])
addjob('Freelance Flutter Developer','Self-Employed','2018 - 2020',[
 'Delivered custom mobile applications for clients, including e-commerce solutions.'])
rightcol=[para('SKILLS','head')]
for label,vals in [
 ('Backend','PHP (Laravel), MySQL, PostgreSQL, SQLite, RESTful API Design'),
 ('Mobile','Flutter and Dart, Bloc, GetX, Provider, Firebase, Firebase Cloud Messaging'),
 ('Frontend','JavaScript, Vue.js, HTML5, CSS3, Bootstrap, Tailwind CSS'),
 ('Architecture','Clean Architecture, MVC, MVVM, SOLID, OOP'),
 ('Tools and Platforms','Git, GitHub, Docker, Postman, Dio/HTTP, CI/CD, Google Maps API'),
 ('Offline Capabilities','Offline-First Applications, Local Workflows, Data Synchronization on Reconnection')]:
    rightcol.append(para(escape(label),'org')); rightcol.append(para(escape(vals),'skill'))
story=[header,Spacer(1,4)]
cols=Table([[leftcol,rightcol]],colWidths=[4.55*inch,2.6*inch])
cols.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),0),('RIGHTPADDING',(0,0),(0,0),.11*inch),('RIGHTPADDING',(1,0),(1,0),0),('TOPPADDING',(0,0),(-1,-1),0),('BOTTOMPADDING',(0,0),(-1,-1),0)]))
story += [cols,PageBreak()]
educol=[para('EDUCATION','head'),para('<b>Bachelor of Computer Science</b>','sub'),
 para('<font color="#007DD5"><b>Benha University, Faculty of Computers and Artificial Intelligence</b></font>','body'),
 para('2016 - 2020','body'),para('Major: Computer Science','body'),para('GPA: 2.6 / 4.0','body'),
 para('LANGUAGES','head'),para('Arabic: Native','body'),para('English: Very Good (Professional Working Proficiency)','body')]
proj=[para('ERP PROJECTS','head'),para('Delivered ERP solutions for seven business sectors:','body')]
for title,desc in [
 ('Accounting ERP','ERP solution for accounting and financial operations.'),
 ('Manufacturing ERP','ERP solution for factory and manufacturing operations.'),
 ('Clinic Management ERP','ERP solution for clinic operations.'),
 ('Pharmacy ERP','ERP solution for pharmacy operations.'),
 ('Supermarket ERP and POS','Retail ERP and point-of-sale solution for supermarket operations.'),
 ('Automotive Spare Parts ERP','ERP solution for automotive spare parts business operations.'),
 ('Restaurant Management ERP','ERP solution for restaurant operations, including a Flutter-based interface.')]:
    proj.extend([para(escape(title),'sub'),para(escape(desc),'body')])
cols2=Table([[educol,proj]],colWidths=[2.6*inch,4.55*inch])
cols2.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),0),('RIGHTPADDING',(0,0),(0,0),.11*inch),('RIGHTPADDING',(1,0),(1,0),0),('TOPPADDING',(0,0),(-1,-1),0),('BOTTOMPADDING',(0,0),(-1,-1),0)]))
story.append(cols2)
pdf.build(story)
print(DOCX_PATH); print(PDF_PATH)
