"""Tech Debt Issuance Chart"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from src.utils.styling import get_theme, EXPORT_DPI, BUBBLE_ZONE, GRAY_DARK, WARNING_ZONE


def plot_tech_debt() -> str:
    plt.rcParams.update(get_theme())
    fig, ax = plt.subplots(figsize=(12, 7))

    years = [2020, 2021, 2022, 2023, 2024, 2025, 2026]
    debt = [25, 30, 28, 25, 30, 121, 125]  # 2026 = mid-range projection
    five_year_avg = float(np.mean(debt[:5]))  # ~27.6

    colors = [GRAY_DARK] * 5 + [BUBBLE_ZONE, WARNING_ZONE]
    hatch = ["", "", "", "", "", "", "//"]  # 2026 hatched

    bars = ax.bar(years, debt, color=colors, edgecolor="white", width=0.6, hatch=hatch)

    # 5-year average line
    ax.axhline(y=five_year_avg, color="#333", linestyle="--", linewidth=2, alpha=0.7)
    ax.text(2020.5, five_year_avg + 3, f"5-Year Avg: ${five_year_avg:.1f}B",
            fontsize=10, fontweight="bold", color="#333")

    # "4x spike" annotation
    ax.annotate("4\u00d7 the\n5-yr average", xy=(2025, 121), xytext=(2023.5, 80),
                arrowprops=dict(arrowstyle="->", color=BUBBLE_ZONE, lw=2),
                fontsize=12, fontweight="bold", color=BUBBLE_ZONE, ha="center")

    # Value labels on bars
    for bar, val in zip(bars, debt):
        ax.text(bar.get_x() + bar.get_width() / 2, val + 2, f"${val}B",
                ha="center", fontsize=9, fontweight="bold")

    ax.set_title("Big Tech Debt Issuance \u2014 The 2025 AI Funding Spike",
                 fontsize=16, fontweight="bold")
    ax.set_xlabel("Year", fontsize=12)
    ax.set_ylabel("Corporate Debt Issuance (Billions USD)", fontsize=12)
    ax.grid(True, alpha=0.3, axis="y")
    ax.set_ylim(0, 150)

    fig.savefig("output/charts/06_tech_debt.png", dpi=EXPORT_DPI,
                facecolor=fig.get_facecolor(), edgecolor="none")
    plt.close(fig)
    return "output/charts/06_tech_debt.png"


def main():
    path = plot_tech_debt()
    print(f"Chart saved: {path}")


if __name__ == "__main__":
    main()
