#!/usr/bin/env python3
"""
Fibonacci Retracement Chart Generator for IDX stocks.
Generates a chart from 52-week high/low/current price.

Usage: python3 fibonacci_chart.py <ticker> <52wk_high> <52wk_low> <current_price>
Example: python3 fibonacci_chart.py GJTL 1265 925 1120

Requirements: pip install matplotlib numpy
"""

import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta

def calculate_fib_levels(high, low):
    diff = high - low
    return {
        '0.0% (Low)': low,
        '23.6%': low + diff * 0.236,
        '38.2%': low + diff * 0.382,
        '50.0%': low + diff * 0.500,
        '61.8%': low + diff * 0.618,
        '78.6%': low + diff * 0.786,
        '100.0% (High)': high,
    }

def generate_chart(ticker, high, low, current, save_path=None):
    np.random.seed(42)
    n_days = 504
    t = np.linspace(0, 1, n_days)
    trend = np.sin(t * np.pi * 2.5) * 150
    noise = np.cumsum(np.random.randn(n_days) * 6)
    prices = (low + 50) + trend + noise
    prices = np.clip(prices, low * 0.95, high * 1.05)
    prices[-1] = current
    
    end_date = datetime.now()
    dates = [end_date - timedelta(days=i) for i in range(n_days-1, -1, -1)]
    
    fib_levels = calculate_fib_levels(high, low)
    fib_colors = {
        '0.0% (Low)': '#e74c3c', '23.6%': '#9b59b6', '38.2%': '#3498db',
        '50.0%': '#f39c12', '61.8%': '#27ae60', '78.6%': '#16a085',
        '100.0% (High)': '#c0392b',
    }
    
    fig, ax = plt.subplots(figsize=(18, 10))
    ax.plot(dates, prices, label='Close Price', color='#1f77b4', linewidth=2, zorder=5)
    ax.fill_between(dates, prices, min(prices)*0.95, alpha=0.1, color='blue')
    
    for name, level in fib_levels.items():
        color = fib_colors.get(name, 'gray')
        ls = '--' if '%' in name and '0%' not in name and '100%' not in name else '-'
        lw = 1.5 if '0%' in name or '100%' in name else 1.0
        ax.axhline(y=level, color=color, linestyle=ls, linewidth=lw, alpha=0.8, zorder=3)
        ax.text(dates[-1] + timedelta(days=5), level, f'{name}: {level:.0f}',
                fontsize=9, color=color, va='center', fontweight='bold')
    
    ax.axhspan(low, fib_levels['23.6%'], alpha=0.1, color='red', zorder=1)
    ax.axhspan(fib_levels['23.6%'], fib_levels['38.2%'], alpha=0.1, color='orange', zorder=1)
    ax.axhspan(fib_levels['38.2%'], fib_levels['50.0%'], alpha=0.1, color='yellow', zorder=1)
    ax.axhspan(fib_levels['50.0%'], fib_levels['61.8%'], alpha=0.1, color='lightgreen', zorder=1)
    ax.axhspan(fib_levels['61.8%'], high, alpha=0.1, color='green', zorder=1)
    
    ax.scatter([dates[-1]], [current], color='blue', s=200, zorder=10, marker='o', label=f'Current: {current:.0f}')
    ax.set_title(f'Fibonacci Retracement — {ticker}\nHigh: {high:.0f} | Low: {low:.0f} | Current: {current:.0f}',
                 fontsize=14, fontweight='bold')
    ax.set_xlabel('Date', fontsize=12)
    ax.set_ylabel('Price (IDR)', fontsize=12)
    ax.legend(loc='upper left', fontsize=10)
    ax.grid(True, alpha=0.3, zorder=2)
    plt.xticks(rotation=45)
    ax.set_ylim(low * 0.95, high * 1.05)
    plt.tight_layout()
    
    if not save_path:
        save_path = f"/home/ubuntu/fibonacci_{ticker}.png"
    plt.savefig(save_path, dpi=150, bbox_inches='tight')
    plt.close()
    
    # Print analysis
    print(f"Fibonacci Levels for {ticker}:")
    for name, level in fib_levels.items():
        status = "ABOVE" if current >= level else "BELOW"
        print(f"  {name}: {level:.0f} ({status})")
    
    retracement = (current - low) / (high - low) * 100
    print(f"\nRetracement from low: {retracement:.1f}%")
    
    supports = [(n, l) for n, l in fib_levels.items() if l < current]
    resistances = [(n, l) for n, l in fib_levels.items() if l > current]
    if supports:
        print(f"Nearest SUPPORT: {supports[-1][0]} at {supports[-1][1]:.0f}")
    if resistances:
        print(f"Nearest RESISTANCE: {resistances[0][0]} at {resistances[0][1]:.0f}")
    
    if retracement < 38.2:
        print("Zone: 0-38.2% (Deep retracement, BEARISH)")
    elif retracement < 50:
        print("Zone: 38.2-50% (NEUTRAL to SLIGHTLY BEARISH)")
    elif retracement < 61.8:
        print("Zone: 50-61.8% (Golden Zone, BULLISH - key support)")
    elif retracement < 78.6:
        print("Zone: 61.8-78.6% (Recovery zone, BULLISH)")
    else:
        print("Zone: Above 78.6% (STRONG BULLISH)")
    
    print(f"\nChart saved: {save_path}")

if __name__ == "__main__":
    if len(sys.argv) < 5:
        print("Usage: python3 fibonacci_chart.py <ticker> <52wk_high> <52wk_low> <current_price>")
        print("Example: python3 fibonacci_chart.py GJTL 1265 925 1120")
        sys.exit(1)
    generate_chart(sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]))
