import pygame
import math
import random
import sys

pygame.init()

# ==========================================
# RAMAYANA: THE BATTLE OF LANKA
# ==========================================

WIDTH, HEIGHT = 1100, 650
FPS = 60

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ramayana - The Battle of Lanka")
clock = pygame.time.Clock()

# Colors
SKY = (113, 174, 210)
DARK = (35, 43, 65)
GOLD = (245, 190, 65)
BLUE = (65, 133, 190)
GREEN = (42, 112, 66)
BROWN = (103, 64, 38)
WHITE = (255, 255, 255)
RED = (190, 45, 45)

FONT = pygame.font.SysFont("georgia", 24, bold=True)
SMALL = pygame.font.SysFont("arial", 17, bold=True)
BIG = pygame.font.SysFont("georgia", 54, bold=True)

WORLD_WIDTH = 4300
GROUND = 540

camera_x = 0
game_over = False
victory = False
started = False

# ==========================================
# HELPER FUNCTIONS
# ==========================================

def text(surface, value, font, color, x, y, center=False):
    image = font.render(value, True, color)
    rect = image.get_rect()

    if center:
        rect.center = (x, y)
    else:
        rect.topleft = (x, y)

    surface.blit(image, rect)


def draw_polygon(surface, color, points):
    pygame.draw.polygon(surface, color, points)


def health_bar(surface, x, y, width, height, current, maximum):
    pygame.draw.rect(surface, (45, 35, 35),
                     (x, y, width, height), border_radius=5)

    amount = max(0, current / maximum)

    pygame.draw.rect(
        surface,
        (65, 190, 90) if amount > 0.35 else RED,
        (x, y, width * amount, height),
        border_radius=5
    )

    pygame.draw.rect(surface, GOLD,
                     (x, y, width, height), 2, border_radius=5)


# ==========================================
# BACKGROUND
# ==========================================

def draw_background(camera):
    screen.fill(SKY)

    # Sun
    pygame.draw.circle(screen, (255, 226, 155), (870, 110), 55)

    # Clouds
    for x in range(-200, WIDTH + 300, 320):
        cx = (x - camera * 0.15) % (WIDTH + 320)
        pygame.draw.circle(screen, (235, 241, 230),
                           (int(cx), 105), 24)
        pygame.draw.circle(screen, (235, 241, 230),
                           (int(cx + 25), 95), 30)
        pygame.draw.circle(screen, (235, 241, 230),
                           (int(cx + 50), 110), 22)

    # Distant mountains
    for x in range(-200, WIDTH + 300, 250):
        px = x - camera * 0.28

        draw_polygon(screen, (93, 126, 132), [
            (px, 440), (px + 110, 240),
            (px + 230, 440)
        ])

        draw_polygon(screen, (220, 227, 211), [
            (px + 110, 240),
            (px + 83, 295),
            (px + 112, 281),
            (px + 133, 300)
        ])

    # Forest
    for x in range(-100, WIDTH + 200, 130):
        px = x - camera * 0.5

        pygame.draw.rect(screen, (89, 61, 40),
                         (px + 40, 350, 22, 180))

        pygame.draw.circle(screen, (35, 103, 61),
                           (int(px + 50), 345), 54)
        pygame.draw.circle(screen, (46, 126, 68),
                           (int(px + 20), 365), 36)
        pygame.draw.circle(screen, (32, 91, 55),
                           (int(px + 83), 370), 38)

    # Lanka palace appears near the end
    palace_x = 3450 - camera

    if -600 < palace_x < WIDTH + 600:
        pygame.draw.rect(screen, (148, 74, 36),
                         (palace_x, 240, 520, 300))

        # Palace towers
        for offset in [20, 130, 260, 390, 490]:
            tx = palace_x + offset

            pygame.draw.rect(screen, (183, 117, 48),
                             (tx, 170, 65, 370))

            draw_polygon(screen, GOLD, [
                (tx - 15, 175),
                (tx + 32, 100),
                (tx + 80, 175)
            ])

            pygame.draw.circle(screen, (255, 220, 115),
                               (tx + 32, 195), 9)

        # Palace windows
        for offset in range(50, 500, 75):
            pygame.draw.rect(screen, (255, 207, 104),
                             (palace_x + offset, 310, 30, 55))

    # Ground
    pygame.draw.rect(screen, (92, 64, 39),
                     (0, GROUND, WIDTH, HEIGHT - GROUND))

    pygame.draw.rect(screen, (66, 135, 64),
                     (0, GROUND, WIDTH, 18))

    # Grass details
    for x in range(0, WIDTH, 30):
        pygame.draw.line(screen, (112, 157, 74),
                         (x, GROUND + 5),
                         (x + 4, GROUND - 3), 2)


# ==========================================
# PLAYER: LORD RAMA
# ==========================================

class Rama:

    def __init__(self):
        self.x = 100
        self.y = GROUND - 110
        self.w = 48
        self.h = 110

        self.vx = 0
        self.vy = 0

        self.speed = 5
        self.jump_power = -15

        self.health = 100
        self.max_health = 100

        self.facing = 1
        self.grounded = False
        self.shoot_cooldown = 0

        self.frame = 0

    def update(self, keys, platforms):

        self.vx = 0

        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.vx = -self.speed
            self.facing = -1

        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.vx = self.speed
            self.facing = 1

        self.x += self.vx
        self.x = max(0, min(WORLD_WIDTH - self.w, self.x))

        self.vy += 0.7
        self.y += self.vy

        self.grounded = False

        # Ground collision
        if self.y + self.h >= GROUND:
            self.y = GROUND - self.h
            self.vy = 0
            self.grounded = True

        # Platform collision
        for platform in platforms:
            rect = pygame.Rect(*platform)

            player_rect = pygame.Rect(
                self.x, self.y, self.w, self.h
            )

            if (
                player_rect.colliderect(rect)
                and self.vy >= 0
                and self.y + self.h - self.vy <= rect.top + 5
            ):
                self.y = rect.top - self.h
                self.vy = 0
                self.grounded = True

        if self.shoot_cooldown > 0:
            self.shoot_cooldown -= 1

        self.frame += 0.15

    def jump(self):
        if self.grounded:
            self.vy = self.jump_power
            self.grounded = False

    def shoot(self, arrows):
        if self.shoot_cooldown == 0:
            arrows.append(
                Arrow(
                    self.x + self.w // 2,
                    self.y + 48,
                    self.facing
                )
            )
            self.shoot_cooldown = 18

    def draw(self, surface, camera):

        x = int(self.x - camera)
        y = int(self.y)

        # Walking animation
        walk = math.sin(self.frame) * 5 if abs(self.vx) > 0 else 0

        # Shadow
        pygame.draw.ellipse(
            surface, (49, 49, 39),
            (x - 8, GROUND - 7, 65, 12)
        )

        # Legs
        pygame.draw.line(surface, (65, 106, 160),
                         (x + 20, y + 75),
                         (x + 15 + walk, y + 105), 10)

        pygame.draw.line(surface, (65, 106, 160),
                         (x + 32, y + 75),
                         (x + 35 - walk, y + 105), 10)

        # Golden sandals
        pygame.draw.line(surface, GOLD,
                         (x + 15 + walk, y + 105),
                         (x + 27 + walk, y + 105), 6)

        pygame.draw.line(surface, GOLD,
                         (x + 35 - walk, y + 105),
                         (x + 47 - walk, y + 105), 6)

        # Dhoti
        draw_polygon(surface, (227, 147, 47), [
            (x + 8, y + 48),
            (x + 41, y + 48),
            (x + 46, y + 83),
            (x + 24, y + 76),
            (x + 5, y + 83)
        ])

        # Body
        pygame.draw.ellipse(surface, BLUE,
                            (x + 7, y + 30, 35, 49))

        # Sash
        pygame.draw.line(surface, GOLD,
                         (x + 10, y + 39),
                         (x + 39, y + 67), 6)

        # Neck
        pygame.draw.rect(surface, BLUE,
                         (x + 17, y + 23, 17, 15))

        # Head
        pygame.draw.circle(surface, (83, 148, 190),
                           (x + 25, y + 20), 17)

        # Hair
        pygame.draw.arc(surface, (45, 32, 28),
                        (x + 8, y + 1, 34, 30),
                        0, math.pi, 5)

        # Eye
        eye_x = x + (33 if self.facing == 1 else 17)
        pygame.draw.circle(surface, WHITE, (eye_x, y + 18), 4)
        pygame.draw.circle(surface, DARK, (eye_x, y + 18), 2)

        # Tilak
        pygame.draw.line(surface, RED,
                         (x + 25, y + 7),
                         (x + 25, y + 18), 3)

        # Crown
        draw_polygon(surface, GOLD, [
            (x + 10, y + 8),
            (x + 15, y - 5),
            (x + 24, y + 1),
            (x + 32, y - 7),
            (x + 40, y + 8)
        ])

        pygame.draw.circle(surface, RED,
                           (x + 25, y + 2), 4)

        # Necklace
        pygame.draw.arc(surface, GOLD,
                        (x + 12, y + 29, 27, 20),
                        0, math.pi, 4)

        # Bow
        bow_x = x + 48 * self.facing

        pygame.draw.arc(
            surface, (116, 67, 28),
            (bow_x - 17, y + 15, 34, 72),
            -math.pi / 2, math.pi / 2, 5
        )

        pygame.draw.line(surface, (242, 222, 180),
                         (bow_x, y + 15),
                         (bow_x, y + 87), 2)


# ==========================================
# DIVINE ARROWS
# ==========================================

class Arrow:

    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.direction = direction
        self.speed = 12
        self.active = True

    def update(self):
        self.x += self.speed * self.direction

        if self.x < 0 or self.x > WORLD_WIDTH:
            self.active = False

    def draw(self, surface, camera):
        x = int(self.x - camera)
        y = int(self.y)

        pygame.draw.line(surface, GOLD,
                         (x, y), (x + 27 * self.direction, y), 4)

        # Arrow head
        draw_polygon(surface, (255, 241, 185), [
            (x + 27 * self.direction, y),
            (x + 17 * self.direction, y - 6),
            (x + 17 * self.direction, y + 6)
        ])

        # Divine glow
        pygame.draw.circle(surface, (255, 214, 88),
                           (x, y), 4)


# ==========================================
# DEMONS
# ==========================================

class Demon:

    def __init__(self, x):
        self.x = x
        self.y = GROUND - 75

        self.health = 40
        self.max_health = 40

        self.speed = random.choice([1.0, 1.5, 2])
        self.direction = -1

        self.attack_timer = 0
        self.alive = True

    def update(self, player):

        if not self.alive:
            return

        distance = player.x - self.x

        if abs(distance) < 330:
            self.direction = 1 if distance > 0 else -1

            if abs(distance) > 55:
                self.x += self.speed * self.direction

        self.attack_timer += 1

        if (
            abs(distance) < 55
            and self.attack_timer > 70
        ):
            player.health -= 8
            self.attack_timer = 0

    def draw(self, surface, camera):

        if not self.alive:
            return

        x = int(self.x - camera)
        y = int(self.y)

        # Body
        pygame.draw.ellipse(surface, (142, 54, 48),
                            (x + 5, y + 22, 45, 48))

        # Armor
        pygame.draw.polygon(surface, (107, 47, 42), [
            (x + 5, y + 32),
            (x + 50, y + 32),
            (x + 44, y + 66),
            (x + 12, y + 66)
        ])

        # Head
        pygame.draw.circle(surface, (177, 78, 58),
                           (x + 27, y + 15), 22)

        # Eyes
        pygame.draw.circle(surface, (255, 217, 74),
                           (x + 19, y + 13), 6)
        pygame.draw.circle(surface, (255, 217, 74),
                           (x + 35, y + 13), 6)

        pygame.draw.circle(surface, DARK, (x + 19, y + 13), 2)
        pygame.draw.circle(surface, DARK, (x + 35, y + 13), 2)

        # Horns
        pygame.draw.polygon(surface, GOLD, [
            (x + 9, y + 1),
            (x - 3, y - 17),
            (x + 18, y - 4)
        ])

        pygame.draw.polygon(surface, GOLD, [
            (x + 44, y + 1),
            (x + 58, y - 17),
            (x + 37, y - 4)
        ])

        # Legs
        pygame.draw.line(surface, DARK,
                         (x + 17, y + 65),
                         (x + 10, y + 76), 8)

        pygame.draw.line(surface, DARK,
                         (x + 38, y + 65),
                         (x + 45, y + 76), 8)

        health_bar(surface, x, y - 30, 55, 7,
                   self.health, self.max_health)


# ==========================================
# RAVANA BOSS
# ==========================================

class Ravana:

    def __init__(self):
        self.x = 3780
        self.y = GROUND - 175

        self.health = 500
        self.max_health = 500

        self.attack_timer = 0
        self.alive = True
        self.active = False

    def update(self, player):

        if not self.alive:
            return

        if abs(player.x - self.x) < 650:
            self.active = True

        if not self.active:
            return

        self.attack_timer += 1

        if self.attack_timer > 110:
            if abs(player.x - self.x) < 500:
                player.health -= 12

            self.attack_timer = 0

    def draw(self, surface, camera):

        if not self.alive:
            return

        x = int(self.x - camera)
        y = int(self.y)

        # Giant body
        pygame.draw.ellipse(surface, (154, 35, 39),
                            (x - 60, y + 65, 120, 105))

        # Golden armor
        pygame.draw.polygon(surface, GOLD, [
            (x - 50, y + 85),
            (x + 50, y + 85),
            (x + 43, y + 155),
            (x - 43, y + 155)
        ])

        # Armor details
        for i in [-25, 0, 25]:
            pygame.draw.circle(surface, RED,
                               (x + i, y + 115), 9)

        # Ten heads
        for i in range(10):
            hx = x - 105 + i * 23

            pygame.draw.circle(surface, (190, 105, 68),
                               (hx, y + 35), 19)

            pygame.draw.circle(surface, (45, 30, 25),
                               (hx - 7, y + 34), 3)

            pygame.draw.circle(surface, (45, 30, 25),
                               (hx + 7, y + 34), 3)

            # Crown
            pygame.draw.polygon(surface, GOLD, [
                (hx - 15, y + 19),
                (hx, y - 12),
                (hx + 15, y + 19)
            ])

            pygame.draw.circle(surface, RED,
                               (hx, y + 7), 4)

        # Arms
        pygame.draw.line(surface, (190, 105, 68),
                         (x - 45, y + 90),
                         (x - 95, y + 125), 17)

        pygame.draw.line(surface, (190, 105, 68),
                         (x + 45, y + 90),
                         (x + 95, y + 125), 17)

        # Legs
        pygame.draw.line(surface, DARK,
                         (x - 30, y + 160),
                         (x - 45, y + 180), 18)

        pygame.draw.line(surface, DARK,
                         (x + 30, y + 160),
                         (x + 45, y + 180), 18)

        health_bar(surface, x - 110, y - 40, 220, 15,
                   self.health, self.max_health)

        text(surface, "RAVANA", SMALL, GOLD, x, y - 70, True)


# ==========================================
# LEVEL OBJECTS
# ==========================================

player = Rama()

arrows = []

demons = [
    Demon(650),
    Demon(1100),
    Demon(1550),
    Demon(2100),
    Demon(2550),
    Demon(3000),
    Demon(3350)
]

boss = Ravana()

platforms = [
    (500, 445, 130, 20),
    (900, 390, 150, 20),
    (1450, 440, 150, 20),
    (1950, 385, 170, 20),
    (2450, 430, 160, 20),
    (2900, 380, 160, 20)
]

# Health collectibles
collectibles = [
    [800, 370, True],
    [1400, 390, True],
    [2200, 335, True],
    [2800, 330, True]
]


# ==========================================
# DRAW LEVEL OBJECTS
# ==========================================

def draw_platforms():
    for x, y, w, h in platforms:
        px = x - camera_x

        pygame.draw.rect(screen, (107, 68, 42),
                         (px, y, w, h), border_radius=5)

        pygame.draw.rect(screen, (79, 143, 66),
                         (px, y, w, 7), border_radius=3)


def draw_collectibles():
    for item in collectibles:
        x, y, available = item

        if available:
            px = int(x - camera_x)

            pygame.draw.circle(screen, GOLD, (px, y), 14)
            pygame.draw.circle(screen, (255, 237, 150),
                               (px, y), 8)

            pygame.draw.circle(screen, WHITE,
                               (px - 3, y - 3), 3)


# ==========================================
# MAIN MENU
# ==========================================

def draw_menu():
    screen.fill((25, 39, 60))

    pygame.draw.circle(screen, (255, 220, 143),
                       (850, 130), 65)

    text(screen, "RAMAYANA", BIG, GOLD, WIDTH // 2, 170, True)

    text(screen, "THE BATTLE OF LANKA",
         FONT, WHITE, WIDTH // 2, 235, True)

    text(screen, "Play as Lord Rama",
         FONT, (160, 210, 240), WIDTH // 2, 330, True)

    text(screen, "Arrow Keys / A-D : Move",
         SMALL, WHITE, WIDTH // 2, 390, True)

    text(screen, "SPACE : Jump",
         SMALL, WHITE, WIDTH // 2, 425, True)

    text(screen, "X : Shoot Divine Arrows",
         SMALL, WHITE, WIDTH // 2, 460, True)

    text(screen, "PRESS ENTER TO BEGIN",
         FONT, GOLD, WIDTH // 2, 540, True)

    pygame.display.flip()


# ==========================================
# GAME LOOP
# ==========================================

running = True

while running:

    clock.tick(FPS)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:

            if not started and event.key == pygame.K_RETURN:
                started = True

            elif started and not game_over:

                if event.key == pygame.K_SPACE:
                    player.jump()

                if event.key == pygame.K_x:
                    player.shoot(arrows)

            elif game_over and event.key == pygame.K_r:

                player = Rama()
                arrows = []

                demons = [
                    Demon(650), Demon(1100),
                    Demon(1550), Demon(2100),
                    Demon(2550), Demon(3000),
                    Demon(3350)
                ]

                boss = Ravana()

                for item in collectibles:
                    item[2] = True

                game_over = False
                victory = False
                camera_x = 0

    if not started:
        draw_menu()
        continue

    if not game_over:

        keys = pygame.key.get_pressed()

        player.update(keys, platforms)

        # Camera follows Rama
        camera_x = max(
            0,
            min(player.x - WIDTH // 2, WORLD_WIDTH - WIDTH)
        )

        # Arrows
        for arrow in arrows:
            arrow.update()

            for demon in demons:
                if demon.alive:
                    enemy_rect = pygame.Rect(
                        demon.x, demon.y, 55, 75
                    )

                    if enemy_rect.collidepoint(
                        arrow.x, arrow.y
                    ):
                        demon.health -= 20
                        arrow.active = False

                        if demon.health <= 0:
                            demon.alive = False

                        break

            if (
                boss.active
                and boss.alive
                and abs(arrow.x - boss.x) < 115
                and boss.y < arrow.y < boss.y + 175
            ):
                boss.health -= 15
                arrow.active = False

                if boss.health <= 0:
                    boss.alive = False

        arrows = [a for a in arrows if a.active]

        # Demons
        for demon in demons:
            demon.update(player)

        # Boss
        boss.update(player)

        # Collectibles
        for item in collectibles:
            x, y, available = item

            if (
                available
                and abs(player.x - x) < 35
                and abs(player.y - y) < 55
            ):
                player.health = min(
                    player.max_health,
                    player.health + 25
                )
                item[2] = False

        # Game state
        player.health = max(0, player.health)

        if player.health <= 0:
            game_over = True

        if not boss.alive:
            victory = True
            game_over = True

    # ======================================
    # RENDER GAME
    # ======================================

    draw_background(camera_x)

    draw_platforms()
    draw_collectibles()

    for demon in demons:
        demon.draw(screen, camera_x)

    boss.draw(screen, camera_x)

    for arrow in arrows:
        arrow.draw(screen, camera_x)

    player.draw(screen, camera_x)

    # HUD
    pygame.draw.rect(screen, (30, 35, 48),
                     (15, 15, 260, 75), border_radius=12)

    text(screen, "LORD RAMA", SMALL, GOLD, 30, 22)

    health_bar(screen, 30, 52, 220, 17,
               player.health, player.max_health)

    text(screen, "LEVEL 1: JOURNEY TO LANKA",
         SMALL, WHITE, WIDTH - 310, 25)

    if boss.active and boss.alive:
        text(screen, "FINAL BATTLE",
             FONT, GOLD, WIDTH // 2, 105, True)

    # Victory / Game over screen
    if game_over:

        overlay = pygame.Surface((WIDTH, HEIGHT))
        overlay.set_alpha(190)
        overlay.fill((10, 12, 25))
        screen.blit(overlay, (0, 0))

        if victory:
            text(screen, "DHARMA TRIUMPHS!",
                 BIG, GOLD, WIDTH // 2, 240, True)

            text(screen, "Ravana has been defeated.",
                 FONT, WHITE, WIDTH // 2, 320, True)

        else:
            text(screen, "GAME OVER",
                 BIG, RED, WIDTH // 2, 250, True)

            text(screen, "Rama's journey has ended.",
                 FONT, WHITE, WIDTH // 2, 320, True)

        text(screen, "PRESS R TO PLAY AGAIN",
             FONT, GOLD, WIDTH // 2, 410, True)

    pygame.display.flip()


pygame.quit()
sys.exit()
