"""
Track 14: HOLLOW - Golden Spiral to Moon (Epic Finale)
"""

import bpy
import math
import random
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils import *


def generate_golden_spiral_points(num_points=300, scale=0.1):
    """Generate points along a golden spiral."""
    phi = (1 + math.sqrt(5)) / 2  # Golden ratio
    points = []
    
    for i in range(num_points):
        t = i / num_points * 6 * math.pi
        r = scale * phi ** (t / (math.pi / 2))
        
        x = r * math.cos(t)
        y = r * math.sin(t)
        z = t * 0.05
        
        points.append((x, y, z))
    
    return points


def create_hollow_animation():
    """Create the full Track 14 animation - the grand finale."""
    clear_scene()
    setup_scene(background_color=COLORS["intro"])  # Deep purple
    
    # Create camera with epic pullback
    camera = create_camera(location=(0, -10, 4), rotation=(1.15, 0, 0))
    
    # Initial orbit
    for frame in range(1, 500):
        t = frame / 500
        angle = t * math.pi * 0.3
        
        x = 10 * math.cos(angle)
        y = -10 * math.sin(angle) - 8
        z = 4 + t * 2
        
        camera.location = (x, y, z)
        camera.keyframe_insert(data_path="location", frame=frame)
    
    # Epic pullback
    for frame in range(500, TOTAL_FRAMES + 1):
        t = (frame - 500) / (TOTAL_FRAMES - 500)
        
        # Pull back and rise
        zoom_out = 1 + t * 0.8
        x = 10 * zoom_out * math.cos(math.pi * 0.3)
        y = (-10 * math.sin(math.pi * 0.3) - 8) * zoom_out
        z = 6 + t * 4
        
        camera.location = (x, y, z)
        camera.keyframe_insert(data_path="location", frame=frame)
    
    # Generate golden spiral
    spiral_points = generate_golden_spiral_points(num_points=300, scale=0.1)
    
    # Create spiral curve
    spiral_data = bpy.data.curves.new(name="GoldenSpiral", type='CURVE')
    spiral_data.dimensions = '3D'
    spiral_data.bevel_depth = 0.03
    spiral_data.bevel_resolution = 6
    
    spline = spiral_data.splines.new('NURBS')
    spline.points.add(len(spiral_points) - 1)
    
    for i, point in enumerate(spiral_points):
        spline.points[i].co = (point[0], point[1], point[2], 1)
    
    spline.use_endpoint_u = True
    spline.order_u = 4
    
    spiral = bpy.data.objects.new("GoldenSpiral", spiral_data)
    bpy.context.collection.objects.link(spiral)
    
    spiral_mat = create_emission_material("SpiralMat", COLORS["hollow"], strength=3.0)
    spiral.data.materials.append(spiral_mat)
    
    # Animate spiral drawing
    spiral_data.bevel_factor_end = 0.0
    spiral_data.keyframe_insert(data_path="bevel_factor_end", frame=1)
    
    spiral_data.bevel_factor_end = 1.0
    spiral_data.keyframe_insert(data_path="bevel_factor_end", frame=300)
    
    # Create Moon
    moon = create_sphere(location=(8, 5, 5), radius=1.5, segments=32, rings=24, name="Moon")
    moon_mat = create_emission_material("MoonMat", (0.996, 0.953, 0.780, 1.0), strength=2.5)
    moon.data.materials.append(moon_mat)
    
    # Moon appears
    keyframe_scale(moon, 1, 0.01)
    keyframe_scale(moon, 200, 0.01)
    keyframe_scale(moon, 280, 1.0)
    
    # Create stars
    stars = []
    star_mat = create_emission_material("StarMat", COLORS["white"], strength=4.0)
    
    for i in range(150):
        pos = (
            random.uniform(-15, 15),
            random.uniform(-15, 15),
            random.uniform(-5, 12)
        )
        
        bpy.ops.mesh.primitive_ico_sphere_add(
            radius=random.uniform(0.02, 0.05),
            subdivisions=1,
            location=pos
        )
        star = bpy.context.active_object
        star.name = f"Star_{i:03d}"
        star.data.materials.append(star_mat)
        
        # Staggered appearance
        appear_frame = 320 + i * 2
        keyframe_scale(star, 1, 0.01)
        keyframe_scale(star, appear_frame, 0.01)
        keyframe_scale(star, appear_frame + 30, 1.0)
        
        stars.append(star)
    
    # Add some additional golden particles along the spiral
    particles = []
    particle_mat = create_emission_material("ParticleMat", COLORS["hollow"], strength=5.0)
    
    for i in range(20):
        idx = int(i / 20 * len(spiral_points))
        pos = spiral_points[idx]
        
        bpy.ops.mesh.primitive_ico_sphere_add(radius=0.06, subdivisions=1, location=pos)
        p = bpy.context.active_object
        p.name = f"SpiralParticle_{i:03d}"
        p.data.materials.append(particle_mat)
        
        # Animate along spiral path
        appear_frame = 30 + int(i / 20 * 270)
        keyframe_scale(p, 1, 0.01)
        keyframe_scale(p, appear_frame, 1.0)
        
        particles.append(p)
    
    # Final glow effect - enlarge moon
    keyframe_scale(moon, 600, 1.0)
    keyframe_scale(moon, 680, 1.3)
    
    # Spiral gets brighter (thicker)
    spiral_data.bevel_depth = 0.03
    spiral_data.keyframe_insert(data_path="bevel_depth", frame=600)
    spiral_data.bevel_depth = 0.05
    spiral_data.keyframe_insert(data_path="bevel_depth", frame=680)
    
    # Gentle fade
    keyframe_scale(moon, TOTAL_FRAMES - 30, 1.3)
    keyframe_scale(moon, TOTAL_FRAMES, 0.01)
    
    return spiral, moon, stars, particles


if __name__ == "__main__":
    create_hollow_animation()
    
    output_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    bpy.ops.wm.save_as_mainfile(filepath=os.path.join(output_dir, "exports", "track14_hollow.blend"))
    
    bpy.ops.export_scene.gltf(
        filepath=os.path.join(output_dir, "exports", "track14_hollow.gltf"),
        export_animations=True,
        export_format='GLTF_SEPARATE'
    )
    
    bpy.ops.wm.alembic_export(
        filepath=os.path.join(output_dir, "exports", "track14_hollow.abc"),
        start=1, end=TOTAL_FRAMES
    )
    
    print("Track 14 - Hollow: Export complete!")
