#!/usr/bin/env python3
"""Unit 1 'My Day' Textbook – Part 1: Setup, Grammar & Vocabulary"""

from docx import Document
from docx.shared import Pt, Inches, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

doc = Document()

# ── Page setup ──
for section in doc.sections:
    section.top_margin = Cm(2)
    section.bottom_margin = Cm(2)
    section.left_margin = Cm(2.5)
    section.right_margin = Cm(2.5)

# ── Styles ──
style = doc.styles['Normal']
font = style.font
font.name = 'Calibri'
font.size = Pt(11)
style.paragraph_format.space_after = Pt(4)
style.paragraph_format.line_spacing = 1.15

# ── Colour palette ──
BLUE_DARK   = RGBColor(0x1a, 0x47, 0x8a)
BLUE_MID    = RGBColor(0x2c, 0x5f, 0x9e)
BLUE_LIGHT  = RGBColor(0x4a, 0x8c, 0xc7)
GRAY         = RGBColor(0x66, 0x66, 0x66)
WHITE        = RGBColor(0xFF, 0xFF, 0xFF)
BG_BLUE      = '1A478A'
BG_LIGHT     = 'F0F4F8'
BG_ROW       = 'E8F0F8'
BG_HEADER    = '1A478A'

# ═══════════════════════════════════════════════════════════════
# HELPERS
# ═══════════════════════════════════════════════════════════════

def set_cell_shading(cell, color):
    """Set background color on a table cell."""
    tcPr = cell._element.get_or_add_tcPr()
    shd = OxmlElement('w:shd')
    shd.set(qn('w:val'), 'clear')
    shd.set(qn('w:color'), 'auto')
    shd.set(qn('w:fill'), color)
    tcPr.append(shd)

def add_title(text, size=18, color=None):
    if color is None:
        color = BLUE_DARK
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = p.add_run(text)
    r.bold = True
    r.font.size = Pt(size)
    r.font.color.rgb = color
    p.paragraph_format.space_after = Pt(4)
    return p

def add_subtitle(text, size=14):
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = p.add_run(text)
    r.bold = True
    r.font.size = Pt(size)
    r.font.color.rgb = BLUE_MID
    p.paragraph_format.space_after = Pt(6)
    return p

def add_section_header(text, level=1):
    doc.add_paragraph()  # spacer
    p = doc.add_paragraph()
    sizes = {1: 14, 2: 13, 3: 12}
    r = p.add_run(text)
    r.bold = True
    r.font.size = Pt(sizes.get(level, 13))
    r.font.color.rgb = BLUE_DARK
    p.paragraph_format.space_before = Pt(8)
    p.paragraph_format.space_after = Pt(6)
    return p

def add_body(text, bold=False, italic=False, indent=0):
    p = doc.add_paragraph()
    if indent:
        p.paragraph_format.left_indent = Cm(indent)
    r = p.add_run(text)
    r.font.size = Pt(11)
    r.bold = bold
    r.italic = italic

def add_code(text):
    """Monospaced example in light blue box."""
    p = doc.add_paragraph()
    p.paragraph_format.left_indent = Cm(0.5)
    r = p.add_run(text)
    r.font.size = Pt(11)
    r.font.name = 'Consolas'
    r.font.color.rgb = BLUE_LIGHT

def make_table(headers, rows, col_widths=None):
    """Create a styled table and return it."""
    table = doc.add_table(rows=len(rows)+1, cols=len(headers))
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.style = 'Table Grid'

    # Header row
    for i, h in enumerate(headers):
        cell = table.cell(0, i)
        set_cell_shading(cell, BG_HEADER)
        p = cell.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        r = p.add_run(h)
        r.bold = True
        r.font.size = Pt(10)
        r.font.color.rgb = WHITE
        r.font.name = 'Calibri'
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER

    # Data rows
    for r_idx, row in enumerate(rows):
        for c_idx, val in enumerate(row):
            cell = table.cell(r_idx+1, c_idx)
            if r_idx % 2 == 0:
                set_cell_shading(cell, BG_LIGHT)
            else:
                set_cell_shading(cell, BG_ROW)
            p = cell.paragraphs[0]
            p.paragraph_format.space_before = Pt(2)
            p.paragraph_format.space_after = Pt(2)
            r = p.add_run(str(val))
            r.font.size = Pt(10)
            r.font.name = 'Calibri'
            cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER

    if col_widths:
        for i, w in enumerate(col_widths):
            for row in table.rows:
                row.cells[i].width = Cm(w)

    doc.add_paragraph()  # spacer after table
    return table

def add_question(num, question_text, options):
    """Add a multiple-choice question."""
    p = doc.add_paragraph()
    r = p.add_run(f'{num}. {question_text}')
    r.bold = True
    r.font.size = Pt(11)

    for opt in options:
        p2 = doc.add_paragraph()
        p2.paragraph_format.left_indent = Cm(1)
        p2.paragraph_format.space_before = Pt(1)
        p2.paragraph_format.space_after = Pt(2)
        r2 = p2.add_run(opt)
        r2.font.size = Pt(11)

def add_dialogue(lines, indent=0.5):
    """Add a dialogue block."""
    for speaker, text in lines:
        p = doc.add_paragraph()
        p.paragraph_format.left_indent = Cm(indent)
        r = p.add_run(f'{speaker}: ')
        r.bold = True
        r.font.size = Pt(11)
        r2 = p.add_run(text)
        r2.font.size = Pt(11)

def add_reading_passage(text, width=15):
    """Add a reading passage in a shaded box."""
    table = doc.add_table(rows=1, cols=1)
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    cell = table.cell(0, 0)
    set_cell_shading(cell, 'F0F4F8')
    p = cell.paragraphs[0]
    p.paragraph_format.left_indent = Cm(0.4)
    p.paragraph_format.right_indent = Cm(0.4)
    p.paragraph_format.space_before = Pt(6)
    p.paragraph_format.space_after = Pt(6)
    r = p.add_run(text)
    r.font.size = Pt(11)
    r.italic = True
    doc.add_paragraph()

def add_page_break():
    doc.add_page_break()

# ═══════════════════════════════════════════════════════════════
# COVER PAGE
# ═══════════════════════════════════════════════════════════════

add_title('5. SINIF İNGİLİZCE', 18)
add_subtitle('ÜNİTE 1: MY DAY — DERS KİTABI', 15)

info = doc.add_paragraph()
info.alignment = WD_ALIGN_PARAGRAPH.CENTER
r = info.add_run('Grammar • Vocabulary • 3 Deneme Sınavı • Okuma Parçaları • Cevap Anahtarı')
r.font.size = Pt(10)
r.font.color.rgb = GRAY

doc.add_paragraph()
meta = doc.add_paragraph()
meta.alignment = WD_ALIGN_PARAGRAPH.CENTER
r = meta.add_run('KKTC KGS Hazırlık  |  Temel Eğitim İngilizce Öğretim Programı')
r.font.size = Pt(9)
r.font.color.rgb = GRAY

# ═══════════════════════════════════════════════════════════════
# GRAMMAR SECTION
# ═══════════════════════════════════════════════════════════════

add_page_break()
add_section_header('BÖLÜM 1: GRAMMAR', 1)
add_body('Bu bölümde Ünite 1\'in üç temel grammar konusunu detaylıca öğreneceksiniz.')

# ── 1.1 Present Simple "to be" ──
add_section_header('1.1  Present Simple — "to be" (am / is / are)', 2)
add_body('"to be" fiili Türkçedeki "olmak" fiilidir. İsim, meslek, yer, yaş ve sıfat belirtirken kullanılır.')

add_body('📌 Olumlu Cümle (Affirmative)', bold=True)
make_table(
    ['Subject', 'to be', 'Türkçe', 'Örnek'],
    [
        ['I', 'am', 'ben ...im', 'I am a student.'],
        ['You', 'are', 'sen ...sin', 'You are happy.'],
        ['He', 'is', 'o (erkek) ...dir', 'He is my father.'],
        ['She', 'is', 'o (kadın) ...dir', 'She is a teacher.'],
        ['It', 'is', 'o (cansız/hayvan) ...dir', 'It is a cat.'],
        ['We', 'are', 'biz ...iz', 'We are friends.'],
        ['You', 'are', 'siz ...siniz', 'You are late.'],
        ['They', 'are', 'onlar ...ler', 'They are at school.'],
    ],
    col_widths=[2.5, 1.5, 3.5, 7.5]
)

add_body('📌 Olumsuz Cümle (Negative)', bold=True)
add_body('Olumsuz yapmak için "not" eklenir: am not / is not (isn\'t) / are not (aren\'t)')
make_table(
    ['Subject', 'Negative', 'Kısa Form', 'Örnek'],
    [
        ['I', 'am not', '(kısa form yok)', 'I am not tired.'],
        ['You', 'are not', "aren't", 'You aren\'t late.'],
        ['He', 'is not', "isn't", 'He isn\'t at home.'],
        ['She', 'is not', "isn't", 'She isn\'t a doctor.'],
        ['It', 'is not', "isn't", 'It isn\'t cold today.'],
        ['We', 'are not', "aren't", 'We aren\'t sad.'],
        ['You', 'are not', "aren't", 'You aren\'t wrong.'],
        ['They', 'are not', "aren't", 'They aren\'t here.'],
    ],
    col_widths=[2.5, 2.5, 3, 7]
)

add_body('📌 Soru Cümlesi (Interrogative)', bold=True)
add_body('Soru yaparken am/is/are öznenin başına gelir.')
make_table(
    ['Soru', 'Cevap (olumlu)', 'Cevap (olumsuz)'],
    [
        ['Am I late?', 'Yes, you are.', 'No, you aren\'t.'],
        ['Are you happy?', 'Yes, I am.', 'No, I\'m not.'],
        ['Is he a student?', 'Yes, he is.', 'No, he isn\'t.'],
        ['Is she your friend?', 'Yes, she is.', 'No, she isn\'t.'],
        ['Is it Monday?', 'Yes, it is.', 'No, it isn\'t.'],
        ['Are we ready?', 'Yes, we are.', 'No, we aren\'t.'],
        ['Are you teachers?', 'Yes, we are.', 'No, we aren\'t.'],
        ['Are they at school?', 'Yes, they are.', 'No, they aren\'t.'],
    ],
    col_widths=[4, 4.5, 4.5]
)

add_body('⚠️ Kısa cevaplarda kısaltma yapılmaz! "Yes, I\'m." ❌ → "Yes, I am." ✅', bold=True)

add_body('📌 Wh- Soruları', bold=True)
make_table(
    ['Soru Kelimesi', 'Anlamı', 'Örnek'],
    [
        ['What', 'Ne', 'What is your name?'],
        ['Where', 'Nerede', 'Where are you from?'],
        ['When', 'Ne zaman', 'When is the exam?'],
        ['Who', 'Kim', 'Who is your teacher?'],
        ['How old', 'Kaç yaşında', 'How old are you?'],
        ['What time', 'Saat kaçta', 'What time is it?'],
        ['What colour', 'Ne renk', 'What colour is your bag?'],
    ],
    col_widths=[3, 3, 9]
)

# ── 1.2 Object Pronouns ──
add_section_header('1.2  Object Pronouns (Nesne Zamirleri)', 2)
add_body('Object pronouns, fiilden ya da edattan (in/at/to/for/look at) sonra gelir. Cümlede nesne görevi görür.')

make_table(
    ['Subject Pronoun', 'Object Pronoun', 'Türkçe', 'Örnek'],
    [
        ['I', 'me', 'beni / bana', 'My mother calls me every day.'],
        ['You', 'you', 'seni / sana', 'I like you.'],
        ['He', 'him', 'onu / ona (erkek)', 'Look at him!'],
        ['She', 'her', 'onu / ona (kadın)', 'I know her.'],
        ['It', 'it', 'onu / ona (cansız)', 'Give it to me.'],
        ['We', 'us', 'bizi / bize', 'She loves us.'],
        ['You', 'you', 'sizi / size', 'We miss you.'],
        ['They', 'them', 'onları / onlara', 'I don\'t like them.'],
    ],
    col_widths=[3, 3, 3, 6]
)

add_body('📌 Önemli Kurallar', bold=True)
add_body('• Fiilden sonra object pronoun gelir:  I love her. ✅  |  I love she. ❌')
add_body('• Edattan (at, to, for, with, before, after) sonra object pronoun gelir:  Look at him. ✅  |  Look at he. ❌')
add_body('• "Give something to someone": give it to me / give them to her / give the book to him')

add_body('📌 Sık Yapılan Hatalar', bold=True)
make_table(
    ['Yanlış ❌', 'Doğru ✅', 'Açıklama'],
    [
        ['Look at he.', 'Look at him.', 'Edattan sonra object pronoun.'],
        ['I like she.', 'I like her.', 'Fiilden sonra object pronoun.'],
        ['Give to me it.', 'Give it to me.', 'Önce nesne, sonra kişi.'],
        ['My father take I.', 'My father takes me.', 'Takes → fiil, sonra "me".'],
    ],
    col_widths=[4, 4, 7]
)

# ── 1.3 Prepositions of Time ──
add_section_header('1.3  Prepositions of Time (Zaman Edatları)', 2)
add_body('Zaman belirten edatlar bir olayın ne zaman olduğunu anlatır.')

make_table(
    ['Edat', 'Kullanım Yeri', 'Örnek'],
    [
        ['at', 'saatlerde', 'I wake up at 7 o\'clock.'],
        ['at', 'özel zamanlarda', 'at night, at noon, at midnight'],
        ['at', 'hafta sonunda', 'at the weekend'],
        ['in', 'günün bölümlerinde', 'in the morning / afternoon / evening'],
        ['in', 'ay ve mevsimlerde', 'in January, in summer'],
        ['in', 'yıllarda', 'in 2026'],
        ['before', '...den önce', 'I brush my teeth before breakfast.'],
        ['before', 'bağlaç olarak', 'before I go to school'],
        ['after', '...den sonra', 'I watch TV after dinner.'],
        ['after', 'bağlaç olarak', 'after I come home'],
    ],
    col_widths=[2.5, 4.5, 8]
)

add_body('📌 before / after detay', bold=True)
add_body('• before + isim:  before school, before breakfast, before dinner')
add_body('• before + cümle:  before I go to bed, before he comes home')
add_body('• after + isim:  after school, after lunch, after the lesson')
add_body('• after + cümle:  after I wake up, after she finishes homework')
add_body('⚠️ before/after\'dan sonra tam cümle gelirse, o cümlenin kendi öznesi olmalıdır!', bold=True)
add_body('   before go to bed ❌ → before I go to bed ✅')

add_body('📌 at / in karşılaştırması', bold=True)
make_table(
    ['Konum', 'at', 'in'],
    [
        ['Saat', 'at 8 o\'clock ✅', 'in 8 o\'clock ❌'],
        ['Günün bölümü', 'at noon / night ✅', 'in the morning ✅'],
        ['Genel kural', 'kesin zaman noktası', 'zaman aralığı / dönem'],
    ],
    col_widths=[4, 5.5, 5.5]
)

# ═══════════════════════════════════════════════════════════════
# VOCABULARY SECTION
# ═══════════════════════════════════════════════════════════════

add_page_break()
add_section_header('BÖLÜM 2: VOCABULARY (KELİME LİSTESİ)', 1)

# ── 2.1 Daily Routines ──
add_section_header('2.1  Daily Routines (Günlük Rutinler)', 3)
add_body('Ünitede geçen temel günlük rutin fiil ve ifadeleri:')

daily_routines = [
    ('wake up', 'uyanmak'),
    ('get up', 'yataktan kalkmak'),
    ('have breakfast', 'kahvaltı yapmak'),
    ('brush teeth', 'diş fırçalamak'),
    ('wash face', 'yüz yıkamak'),
    ('wash hands', 'el yıkamak'),
    ('get dressed', 'giyinmek'),
    ('comb hair', 'saç taramak'),
    ('go to school', 'okula gitmek'),
    ('have lunch', 'öğle yemeği yemek'),
    ('come home', 'eve gelmek'),
    ('do homework', 'ödev yapmak'),
    ('have dinner', 'akşam yemeği yemek'),
    ('watch TV', 'televizyon izlemek'),
    ('read a book', 'kitap okumak'),
    ('take a shower', 'duş almak'),
    ('go to bed', 'yatmak / uyumaya gitmek'),
    ('sleep', 'uyumak'),
    ('play with friends', 'arkadaşlarla oynamak'),
    ('listen to music', 'müzik dinlemek'),
]

make_table(
    ['No', 'English', 'Türkçe'],
    [(str(i), e, t) for i, (e, t) in enumerate(daily_routines, 1)],
    col_widths=[1, 7, 7]
)

# ── 2.2 Times ──
add_section_header('2.2  Times (Saatler / Zaman İfadeleri)', 3)

times = [
    ("o'clock", 'saat (tam)'),
    ('half past', 'buçuk'),
    ('quarter past', 'çeyrek geçe'),
    ('quarter to', 'çeyrek kala'),
    ('a.m.', 'öğleden önce (00:00–11:59)'),
    ('p.m.', 'öğleden sonra (12:00–23:59)'),
    ('midnight', 'gece yarısı (00:00)'),
    ('noon', 'öğlen (12:00)'),
]

make_table(
    ['No', 'English', 'Türkçe'],
    [(str(i), e, t) for i, (e, t) in enumerate(times, 1)],
    col_widths=[1, 7, 7]
)

add_body('📌 Saat Söyleme Örnekleri', bold=True)
make_table(
    ['Saat', 'Söylenişi'],
    [
        ['07:00', "It's seven o'clock."],
        ['07:30', "It's half past seven."],
        ['07:15', "It's quarter past seven."],
        ['07:45', "It's quarter to eight."],
        ['08:00 a.m.', "It's eight a.m. (sabah 8)"],
        ['08:00 p.m.', "It's eight p.m. (akşam 8)"],
    ],
    col_widths=[3, 12]
)

# ── 2.3 Body Parts ──
add_section_header('2.3  Body Parts (Vücut Bölümleri)', 3)

body_parts = [
    ('head', 'baş / kafa'),
    ('shoulders', 'omuzlar'),
    ('knees', 'dizler'),
    ('toes', 'ayak parmakları'),
    ('eyes', 'gözler'),
    ('ears', 'kulaklar'),
    ('mouth', 'ağız'),
    ('nose', 'burun'),
    ('arms', 'kollar'),
    ('hands', 'eller'),
    ('fingers', 'parmaklar (el)'),
    ('legs', 'bacaklar'),
    ('feet', 'ayaklar'),
    ('hair', 'saç'),
    ('face', 'yüz'),
]

make_table(
    ['No', 'English', 'Türkçe'],
    [(str(i), e, t) for i, (e, t) in enumerate(body_parts, 1)],
    col_widths=[1, 7, 7]
)

add_body('\n📌 Vücut Bölümleriyle İlgili Örnek Cümleler', bold=True)
add_body('• My eyes are brown.')
add_body('• His hair is short and black.')
add_body('• Her hands are small.')
add_body('• Your face is clean.')
add_body('• My knees are sore after the game.')
add_body('• I brush my teeth every morning.')
add_body('• Wash your hands before lunch!')

# ═══════════════════════════════════════════════════════════════
# SAVE PART 1
# ═══════════════════════════════════════════════════════════════

doc.save('/root/Akademik/İngilizce/5. Sınıf/Unit1_My_Day_Kitap.docx')
print('Part 1 saved successfully.')
