#!/usr/bin/env python3
"""CurriVerse X planar motion lab / آزمایش حرکت دوبعدی.
Run: python3 ee-motion-2d.py vx0 vy0 g T
SI: m/s,m/s,m/s^2,s. Fixed r0=(0,0), ax=0, ay=-g, no collision surface.
Half-unit values: velocities -4..12; g 1/2..12; T 1/2..6.
Standard library only; exact component arithmetic and floating-point norm/quadrature.
"""
import argparse
from fractions import Fraction as F
import json
import math


def number(text):
    try:value=F(text)
    except (ValueError,ZeroDivisionError):raise argparse.ArgumentTypeError('Use a finite number or fraction such as -1/2.')
    if (2*value).denominator!=1:raise argparse.ArgumentTypeError('Use half-unit steps.')
    return value


def analyze(vx0,vy0,g,T):
    vx0,vy0,g,T=map(F,(vx0,vy0,g,T))
    if not (-4<=vx0<=12 and -4<=vy0<=12 and F(1,2)<=g<=12 and F(1,2)<=T<=6):raise ValueError('Use velocities -4..12, g 1/2..12, T 1/2..6.')
    def pos(t):return [vx0*t,vy0*t-g*t*t/2]
    def vel(t):return [vx0,vy0-g*t]
    def speed(t):return math.hypot(*map(float,vel(t)))
    position=pos(T);velocity=vel(T);average=[z/T for z in position];initial_speed=math.hypot(float(vx0),float(vy0));chord=math.hypot(*map(float,position))
    assert average==[vx0,vy0-g*T/2]
    assert velocity[1]**2-vy0**2==-2*g*position[1]
    direction=math.degrees(math.atan2(float(vy0),float(vx0)))%360 if initial_speed else None
    unit=[float(vx0)/initial_speed,float(vy0)/initial_speed] if initial_speed else None
    apex=vy0/g;inside=0<apex<T;ret=2*vy0/g if vy0>0 else None
    bounds=[];check_error=0.0
    for n in (8,16):
        h=T/n;m=sum(speed((F(i)+F(1,2))*h)*float(h) for i in range(n))
        trap=(speed(0)/2+sum(speed(i*h) for i in range(1,n))+speed(T)/2)*float(h)
        signed=[sum(float(vel((F(i)+F(1,2))*h)[j]*h) for i in range(n)) for j in (0,1)]
        check_error=max(check_error,*[abs(z-float(w))/max(1,abs(float(w))) for z,w in zip(signed,position)])
        assert chord<=m+1e-9*max(1,m) and m<=trap+1e-9*max(1,trap)
        bounds.append({'n':n,'midpoint_m':m,'trapezoid_m':trap,'gap_m':max(0,trap-m)})
    assert bounds[0]['midpoint_m']<=bounds[1]['midpoint_m']+1e-9
    assert bounds[1]['trapezoid_m']<=bounds[0]['trapezoid_m']+1e-9
    assert check_error<=1e-9
    strings=lambda v:[str(x) for x in v]
    return {'position_m':strings(position),'velocity_m_s':strings(velocity),'average_velocity_m_s':strings(average),
            'speed_m_s':speed(T),'chord_m':chord,'initial_direction_deg':direction,'initial_unit_direction':unit,
            'interior_apex':inside,'apex_time_s':str(apex) if inside else None,'apex_position_m':strings(pos(apex)) if inside else None,
            'return_time_s':str(ret) if ret is not None else None,'return_within_interval':ret is not None and ret<=T,
            'distance_bounds':bounds,'scaled_check_error':check_error,'agreement':'exact components; numerical distance bounds'}


def main():
    p=argparse.ArgumentParser(usage='%(prog)s [--json] vx0 vy0 g T',description='Planar constant-acceleration motion, directions and midpoint/trapezoid distance estimates.')
    p.add_argument('--json',action='store_true');args,inputs=p.parse_known_args()
    if len(inputs)!=4:p.error('Provide exactly four inputs: vx0,vy0,g,T.')
    try:values=[number(x) for x in inputs];result=analyze(*values)
    except (argparse.ArgumentTypeError,ValueError) as e:p.error(str(e))
    if args.json:print(json.dumps(result));return
    print('SI planar model; g is a chosen teaching value / مدل دوبعدی SI؛ g مقدار آموزشی انتخابی است')
    print('No ground collision; quadrature bounds have floating-point rounding. / برخورد زمین مدل نمی‌شود؛ کران‌های عددی گردکردن ممیز شناور دارند.')
    for key,value in result.items():print(key+': '+json.dumps(value,ensure_ascii=False))


if __name__=='__main__':main()
