#!/usr/bin/env python3
"""Seed proper cascading goal hierarchy for the demo company."""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import create_app, db
from app.models import Goal, GoalMetric
from datetime import datetime, timezone, timedelta

app = create_app()

with app.app_context():
    company_id = 'c672720f-7bb4-4c02-aaba-eaacfddb22c7'  # Greenfield Landscaping

    # Clear existing goals (cascade delete via relationship)
    old_goals = Goal.query.filter_by(company_id=company_id).all()
    for g in reversed(old_goals):  # Delete children first
        db.session.delete(g)
    db.session.commit()
    print(f"Deleted {len(old_goals)} old goals")

    now = datetime.now(timezone.utc)
    q3_start = now.replace(month=7, day=1, hour=0, minute=0, second=0, microsecond=0)
    q3_end = now.replace(month=9, day=30, hour=23, minute=59, second=59, microsecond=0)

    # === ORG LEVEL ===
    org_goal = Goal(
        company_id=company_id,
        name='Q3 2025 Revenue Target',
        description='Achieve $500K in Q3 revenue across all departments',
        level='org',
        target_value=500000.0,
        current_value=312500.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=1.0,
    )
    db.session.add(org_goal)
    db.session.flush()

    # === DEPARTMENT LEVEL ===
    dept_sales = Goal(
        company_id=company_id,
        parent_goal_id=org_goal.id,
        name='Sales Department',
        description='Drive $300K in direct sales revenue',
        level='department',
        target_value=300000.0,
        current_value=195000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.6,
    )
    db.session.add(dept_sales)
    db.session.flush()

    dept_marketing = Goal(
        company_id=company_id,
        parent_goal_id=org_goal.id,
        name='Marketing Department',
        description='Generate $150K in marketing-sourced revenue',
        level='department',
        target_value=150000.0,
        current_value=87500.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.3,
    )
    db.session.add(dept_marketing)
    db.session.flush()

    dept_operations = Goal(
        company_id=company_id,
        parent_goal_id=org_goal.id,
        name='Operations Department',
        description='Maintain $50K in operational cost savings',
        level='department',
        target_value=50000.0,
        current_value=30000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.1,
    )
    db.session.add(dept_operations)
    db.session.flush()

    # === TEAM LEVEL (under Sales) ===
    team_enterprise = Goal(
        company_id=company_id,
        parent_goal_id=dept_sales.id,
        name='Enterprise Sales Team',
        description='Close enterprise deals worth $150K',
        level='team',
        target_value=150000.0,
        current_value=105000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.5,
    )
    db.session.add(team_enterprise)
    db.session.flush()

    team_smb = Goal(
        company_id=company_id,
        parent_goal_id=dept_sales.id,
        name='SMB Sales Team',
        description='Close SMB deals worth $150K',
        level='team',
        target_value=150000.0,
        current_value=90000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.5,
    )
    db.session.add(team_smb)
    db.session.flush()

    # === TEAM LEVEL (under Marketing) ===
    team_digital = Goal(
        company_id=company_id,
        parent_goal_id=dept_marketing.id,
        name='Digital Marketing',
        description='Sourced revenue from digital campaigns',
        level='team',
        target_value=100000.0,
        current_value=62000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.67,
    )
    db.session.add(team_digital)
    db.session.flush()

    team_events = Goal(
        company_id=company_id,
        parent_goal_id=dept_marketing.id,
        name='Events & Partnerships',
        description='Revenue from trade shows and partner channels',
        level='team',
        target_value=50000.0,
        current_value=25500.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.33,
    )
    db.session.add(team_events)
    db.session.flush()

    # === TEAM LEVEL (under Operations) ===
    team_ops = Goal(
        company_id=company_id,
        parent_goal_id=dept_operations.id,
        name='Cost Optimization',
        description='Reduce operational costs by $50K through efficiency gains',
        level='team',
        target_value=50000.0,
        current_value=30000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=1.0,
    )
    db.session.add(team_ops)
    db.session.flush()

    # === REP LEVEL (under Enterprise) ===
    rep1 = Goal(
        company_id=company_id,
        parent_goal_id=team_enterprise.id,
        name='Sarah Chen — Enterprise Rep',
        description='Individual quota for enterprise segment',
        level='rep',
        target_value=50000.0,
        current_value=42000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.33,
    )
    db.session.add(rep1)
    db.session.flush()

    rep2 = Goal(
        company_id=company_id,
        parent_goal_id=team_enterprise.id,
        name='Marcus Johnson — Enterprise Rep',
        description='Individual quota for enterprise segment',
        level='rep',
        target_value=50000.0,
        current_value=35000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.33,
    )
    db.session.add(rep2)
    db.session.flush()

    rep3 = Goal(
        company_id=company_id,
        parent_goal_id=team_enterprise.id,
        name='Priya Patel — Enterprise Rep',
        description='Individual quota for enterprise segment',
        level='rep',
        target_value=50000.0,
        current_value=28000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.34,
    )
    db.session.add(rep3)
    db.session.flush()

    # === REP LEVEL (under SMB) ===
    rep4 = Goal(
        company_id=company_id,
        parent_goal_id=team_smb.id,
        name='Alex Rivera — SMB Rep',
        description='Individual quota for SMB segment',
        level='rep',
        target_value=50000.0,
        current_value=33000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.33,
    )
    db.session.add(rep4)
    db.session.flush()

    rep5 = Goal(
        company_id=company_id,
        parent_goal_id=team_smb.id,
        name='Jordan Lee — SMB Rep',
        description='Individual quota for SMB segment',
        level='rep',
        target_value=50000.0,
        current_value=31000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.33,
    )
    db.session.add(rep5)
    db.session.flush()

    rep6 = Goal(
        company_id=company_id,
        parent_goal_id=team_smb.id,
        name='Casey Kim — SMB Rep',
        description='Individual quota for SMB segment',
        level='rep',
        target_value=50000.0,
        current_value=26000.0,
        unit='$',
        start_date=q3_start,
        end_date=q3_end,
        status='active',
        weight=0.34,
    )
    db.session.add(rep6)
    db.session.flush()

    db.session.commit()
    print(f"Created 16 goals in hierarchy")

    # === METRICS ===
    metrics_data = [
        # Org metrics
        (org_goal.id, 'Total Revenue', 500000, 312500, '$', 'quarterly'),
        (org_goal.id, 'Deal Count', 50, 31, 'count', 'quarterly'),
        (org_goal.id, 'Win Rate', 45.0, 42.5, '%', 'quarterly'),
        # Sales Dept
        (dept_sales.id, 'Closed Revenue', 300000, 195000, '$', 'quarterly'),
        (dept_sales.id, 'Deals Closed', 30, 18, 'count', 'quarterly'),
        (dept_sales.id, 'Avg Deal Size', 10000, 10833, '$', 'quarterly'),
        # Marketing Dept
        (dept_marketing.id, 'MQLs Generated', 200, 145, 'count', 'quarterly'),
        (dept_marketing.id, 'SQLs Converted', 80, 52, 'count', 'quarterly'),
        (dept_marketing.id, 'Marketing Sourced Revenue', 150000, 87500, '$', 'quarterly'),
        # Operations
        (dept_operations.id, 'Cost Savings', 50000, 30000, '$', 'quarterly'),
        (dept_operations.id, 'Efficiency Score', 95.0, 88.0, '%', 'quarterly'),
        # Enterprise Team
        (team_enterprise.id, 'Enterprise Deals', 15, 10, 'count', 'quarterly'),
        (team_enterprise.id, 'Enterprise Revenue', 150000, 105000, '$', 'quarterly'),
        # SMB Team
        (team_smb.id, 'SMB Deals', 25, 15, 'count', 'quarterly'),
        (team_smb.id, 'SMB Revenue', 150000, 90000, '$', 'quarterly'),
        # Digital Marketing
        (team_digital.id, 'Campaign ROI', 3.5, 2.8, 'x', 'quarterly'),
        (team_digital.id, 'Digital Revenue', 100000, 62000, '$', 'quarterly'),
        # Events
        (team_events.id, 'Event Leads', 100, 60, 'count', 'quarterly'),
        (team_events.id, 'Events Revenue', 50000, 25500, '$', 'quarterly'),
        # Ops
        (team_ops.id, 'Process Automations', 10, 7, 'count', 'quarterly'),
        (team_ops.id, 'Savings Delivered', 50000, 30000, '$', 'quarterly'),
    ]

    for goal_id, metric_name, target, actual, unit, period in metrics_data:
        gm = GoalMetric(
            goal_id=goal_id,
            metric_name=metric_name,
            target_value=target,
            actual_value=actual,
            unit=unit,
            period=period,
            period_start=q3_start,
            period_end=q3_end,
        )
        db.session.add(gm)

    db.session.commit()
    print(f"Created {len(metrics_data)} goal metrics")
    print("Done!")