from fpdf import FPDF

output_path = r"C:\Users\wsu\Downloads\viz\Iowa_Grain_Stocks_March2026.pdf"

class PDF(FPDF):
    def header(self):
        self.set_font('Helvetica', 'B', 10)
        self.set_text_color(100, 100, 100)
        self.cell(0, 8, 'USDA Grain Stocks | Iowa | March 2026', align='R', new_x="LMARGIN", new_y="NEXT")
        self.line(10, self.get_y(), 200, self.get_y())
        self.ln(4)

    def footer(self):
        self.set_y(-15)
        self.set_font('Helvetica', 'I', 8)
        self.set_text_color(150, 150, 150)
        self.cell(0, 10, f'Page {self.page_no()}/{{nb}}', align='C')

    def section_title(self, title):
        self.set_font('Helvetica', 'B', 13)
        self.set_text_color(26, 60, 94)
        self.cell(0, 10, title, new_x="LMARGIN", new_y="NEXT")
        self.ln(2)

    def add_table(self, headers, data, col_widths, highlight_color=None):
        # Header row
        self.set_font('Helvetica', 'B', 9)
        self.set_fill_color(26, 60, 94)
        self.set_text_color(255, 255, 255)
        for i, h in enumerate(headers):
            align = 'L' if i == 0 else 'R'
            self.cell(col_widths[i], 8, h, border=1, fill=True, align=align)
        self.ln()

        # Data rows
        self.set_font('Helvetica', '', 9)
        for ri, row in enumerate(data):
            is_last = (ri == len(data) - 1)
            if is_last and highlight_color:
                self.set_fill_color(*highlight_color)
                self.set_font('Helvetica', 'B', 9)
            elif ri % 2 == 1:
                self.set_fill_color(245, 245, 245)
            else:
                self.set_fill_color(255, 255, 255)
            self.set_text_color(30, 30, 30)

            for i, val in enumerate(row):
                align = 'L' if i == 0 else 'R'
                self.cell(col_widths[i], 7, val, border=1, fill=True, align=align)
            self.ln()
            if is_last:
                self.set_font('Helvetica', '', 9)
        self.ln(2)

    def bullet(self, text):
        self.set_font('Helvetica', '', 9)
        self.set_text_color(50, 50, 50)
        x = self.get_x()
        self.cell(8, 5, '-')
        self.set_x(x + 8)
        self.multi_cell(0, 5, text)
        self.ln(1)


pdf = PDF()
pdf.alias_nb_pages()
pdf.set_auto_page_break(auto=True, margin=20)
pdf.add_page()

# Title
pdf.set_font('Helvetica', 'B', 22)
pdf.set_text_color(26, 60, 94)
pdf.cell(0, 14, 'Iowa Grain Stocks Report', align='C', new_x="LMARGIN", new_y="NEXT")
pdf.set_font('Helvetica', '', 11)
pdf.set_text_color(100, 100, 100)
pdf.cell(0, 8, 'March 1, 2025 vs 2026  |  Released March 31, 2026', align='C', new_x="LMARGIN", new_y="NEXT")
pdf.ln(2)
pdf.set_font('Helvetica', 'I', 8)
pdf.set_text_color(150, 150, 150)
pdf.cell(0, 5, 'Source: NASS, USDA. All figures in 1,000 bushels. (D) = withheld. (NA) = not available.', align='C', new_x="LMARGIN", new_y="NEXT")
pdf.ln(6)

# --- CORN ---
pdf.section_title('1. Corn Stocks')
cw = [30, 35, 35, 40, 35]
pdf.add_table(
    ['', 'On Farms', 'Off Farms', 'Total', 'YoY %'],
    [
        ['2025', '790,000', '681,769', '1,471,769', ''],
        ['2026', '980,000', '598,826', '1,578,826', ''],
        ['Delta', '+24.1%', '-12.2%', '+7.3%', '+107K'],
    ],
    cw, highlight_color=(200, 230, 200)
)
pdf.bullet('On-farm stocks surged +24% (790M -> 980M) -- farmers holding grain')
pdf.bullet('Off-farm (elevators) declined -12% -- commercial drawdown')
pdf.bullet('Total Iowa corn stocks: 1.579 billion bushels, +7.3% YoY')

# --- SOYBEANS ---
pdf.section_title('2. Soybean Stocks')
pdf.add_table(
    ['', 'On Farms', 'Off Farms', 'Total', 'YoY %'],
    [
        ['2025', '160,000', '199,894', '359,894', ''],
        ['2026', '155,000', '203,351', '358,351', ''],
        ['Delta', '-3.1%', '+1.7%', '-0.4%', '-1.5K'],
    ],
    cw, highlight_color=(255, 240, 210)
)
pdf.bullet('Virtually flat year-over-year (-0.4%)')
pdf.bullet('Slight shift: on-farm down 3%, off-farm up 1.7%')

# --- WHEAT ---
pdf.section_title('3. All Wheat Stocks')
pdf.add_table(
    ['', 'On Farms', 'Off Farms', 'Total', 'YoY %'],
    [
        ['2025', 'N/A', '3,012', '3,012', ''],
        ['2026', 'N/A', '936', '936', ''],
        ['Delta', '--', '-68.9%', '-68.9%', '-2,076'],
    ],
    cw, highlight_color=(252, 220, 220)
)
pdf.bullet('Off-farm wheat stocks collapsed -69% (3,012 -> 936)')
pdf.bullet('Iowa is minor wheat state; no on-farm wheat storage reported')

# --- OATS ---
pdf.section_title('4. Oats Stocks')
cw2 = [30, 45, 45, 45]
pdf.add_table(
    ['', 'On Farms', 'Off Farms', 'Total'],
    [
        ['2025', '1,550', '(D)', '(D)'],
        ['2026', '1,550', '(D)', '(D)'],
        ['Delta', '0%', '--', '--'],
    ],
    cw2, highlight_color=(230, 230, 230)
)
pdf.bullet('On-farm flat at 1,550. Off-farm data withheld.')

# --- SORGHUM & BARLEY ---
pdf.section_title('5. Sorghum & Barley')
pdf.set_font('Helvetica', '', 9)
pdf.set_text_color(80, 80, 80)
pdf.multi_cell(0, 5, 'Iowa is not a major producer. All data withheld (D) or not available (NA) for both 2025 and 2026.')
pdf.ln(6)

# ============= SUMMARY TABLE =============
pdf.section_title('Summary: Iowa Grain Stocks (1,000 bu)')

cw3 = [35, 40, 40, 30, 30]
pdf.set_font('Helvetica', 'B', 9)
pdf.set_fill_color(46, 125, 50)
pdf.set_text_color(255, 255, 255)
headers = ['Crop', '2025 Total', '2026 Total', 'YoY %', 'Signal']
for i, h in enumerate(headers):
    a = 'L' if i == 0 else 'R'
    pdf.cell(cw3[i], 8, h, border=1, fill=True, align=a)
pdf.ln()

summary = [
    ('Corn', '1,471,769', '1,578,826', '+7.3%', 'Bearish'),
    ('Soybeans', '359,894', '358,351', '-0.4%', 'Neutral'),
    ('Wheat', '3,012', '936', '-68.9%', 'Bullish'),
    ('Oats', '(D)', '(D)', '--', '--'),
    ('Sorghum', '(D)', '(D)', '--', '--'),
    ('Barley', '(D)', '(D)', '--', '--'),
]

pdf.set_font('Helvetica', '', 9)
for ri, row in enumerate(summary):
    if ri % 2 == 0:
        pdf.set_fill_color(255, 255, 255)
    else:
        pdf.set_fill_color(245, 245, 245)
    pdf.set_text_color(30, 30, 30)

    # Color the signal
    for i, val in enumerate(row):
        a = 'L' if i == 0 else 'R'
        if i == 4:
            if val == 'Bearish':
                pdf.set_text_color(200, 50, 50)
                pdf.set_font('Helvetica', 'B', 9)
            elif val == 'Bullish':
                pdf.set_text_color(30, 130, 50)
                pdf.set_font('Helvetica', 'B', 9)
            else:
                pdf.set_text_color(100, 100, 100)
                pdf.set_font('Helvetica', '', 9)
        pdf.cell(cw3[i], 7, val, border=1, fill=True, align=a)
        pdf.set_text_color(30, 30, 30)
        pdf.set_font('Helvetica', '', 9)
    pdf.ln()

pdf.ln(8)

# Key takeaways
pdf.section_title('Key Takeaways')
pdf.bullet('CORN: Elevated stocks + farmer hoarding = supply overhang. Bearish for corn prices.')
pdf.bullet('SOYBEANS: Stable. No significant change in supply picture.')
pdf.bullet('WHEAT: Sharp drawdown in off-farm stocks (-69%). Bullish signal, but Iowa is a minor wheat state.')
pdf.bullet('Overall: Iowa corn stocks significantly above prior year. Watch for farmer selling pace in Q2.')

pdf.output(output_path)
print(f"PDF saved: {output_path}")
