"""
Workflow Seeder - Seeds Phase 1 Critical Workflows

Phase 1 Critical Workflows:
1. Journal Entry Approval (journal_entry)
2. Vendor Payment Approval (vendor_payment)
3. Sales Credit Note Approval (sales_credit_note)
4. Bad Debt Write-off Approval (bad_debt_writeoff)
5. Period Close Approval (period_close)

These workflows are IFRS compliant and implement proper segregation of duties.
"""
import uuid
from typing import Dict, List, Optional, Tuple
from sqlalchemy.orm import Session
from sqlalchemy import and_

from app.models.workflow import (
    WorkflowDefinition, WorkflowState, WorkflowTransition,
    WorkflowStatus, WorkflowActionType
)
from app.models.role import Role
from app.constants.workflow_entity_types import (
    JOURNAL_ENTRY, VENDOR_PAYMENT, SALES_CREDIT_NOTE,
    BAD_DEBT_WRITEOFF, PERIOD_CLOSE, ENTITY_TYPE_LABELS
)


class WorkflowSeeder:
    """Seeds Phase 1 critical workflows into the database"""

    def __init__(self, db: Session):
        self.db = db
        self.roles: Dict[str, str] = {}  # role_name -> role_id mapping
        self._load_roles()

    def _load_roles(self):
        """Load existing roles from database"""
        roles = self.db.query(Role).filter(Role.is_active == True).all()
        self.roles = {r.name: r.id for r in roles}

        # Create workflow-specific roles if they don't exist
        required_roles = [
            ("finance_manager", "Finance Manager - Approves financial transactions"),
            ("finance_director", "Finance Director - Senior financial approval authority"),
            ("cfo", "Chief Financial Officer - Highest financial authority"),
            ("ceo", "Chief Executive Officer - Executive approval authority"),
            ("credit_controller", "Credit Controller - Manages credit and collections"),
        ]

        for role_name, description in required_roles:
            if role_name not in self.roles:
                role = Role(
                    id=str(uuid.uuid4()),
                    name=role_name,
                    description=description,
                    is_system_role=True,
                    is_active=True
                )
                self.db.add(role)
                self.db.flush()
                self.roles[role_name] = role.id

    def _get_role_ids(self, role_names: List[str]) -> List[str]:
        """Get role IDs for given role names"""
        return [self.roles[name] for name in role_names if name in self.roles]

    def _workflow_exists(self, code: str) -> bool:
        """Check if workflow already exists"""
        return self.db.query(WorkflowDefinition).filter(
            WorkflowDefinition.code == code
        ).first() is not None

    def seed_all_phase1(self) -> Dict[str, WorkflowDefinition]:
        """Seed all Phase 1 workflows"""
        results = {}

        # 1. Journal Entry Approval
        if not self._workflow_exists("JOURNAL_ENTRY_APPROVAL"):
            results['journal_entry'] = self._seed_journal_entry_workflow()

        # 2. Vendor Payment Approval
        if not self._workflow_exists("VENDOR_PAYMENT_APPROVAL"):
            results['vendor_payment'] = self._seed_vendor_payment_workflow()

        # 3. Sales Credit Note Approval
        if not self._workflow_exists("SALES_CREDIT_NOTE_APPROVAL"):
            results['sales_credit_note'] = self._seed_sales_credit_note_workflow()

        # 4. Bad Debt Write-off Approval
        if not self._workflow_exists("BAD_DEBT_WRITEOFF_APPROVAL"):
            results['bad_debt_writeoff'] = self._seed_bad_debt_writeoff_workflow()

        # 5. Period Close Approval
        if not self._workflow_exists("PERIOD_CLOSE_APPROVAL"):
            results['period_close'] = self._seed_period_close_workflow()

        self.db.commit()
        return results

    # ==================== 1. JOURNAL ENTRY WORKFLOW ====================
    def _seed_journal_entry_workflow(self) -> WorkflowDefinition:
        """
        Journal Entry Approval Workflow

        IFRS: IAS 8 - Accounting Policies, Changes in Accounting Estimates and Errors

        Flow: Draft -> Submitted -> Manager Review -> Finance Controller -> Posted

        Critical Controls:
        - No self-approval permitted
        - Reversing entries require original approver + 1
        - Year-end adjustments require CFO approval
        - Entries > $50,000 require Finance Director
        """
        workflow = WorkflowDefinition(
            id=str(uuid.uuid4()),
            name="Journal Entry Approval",
            code="JOURNAL_ENTRY_APPROVAL",
            module="accounting",
            description="Approval workflow for manual journal entries. IFRS compliant with proper segregation of duties. ALL manual journals require approval - no self-approval permitted.",
            is_active=True,
            is_default=True,
            requires_approval=True,
            auto_submit=False,
            approval_threshold_amount=0,  # All entries require approval
            max_approval_levels=4
        )
        self.db.add(workflow)
        self.db.flush()

        # States
        states = self._create_states(workflow.id, [
            ("Draft", "DRAFT", WorkflowStatus.DRAFT, True, False, False, "#6b7280", "file-earmark", 1, [], []),
            ("Submitted", "SUBMITTED", WorkflowStatus.SUBMITTED, False, False, False, "#3b82f6", "send", 2, [], ["accountant", "manager"]),
            ("Manager Review", "PENDING_MGR", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#f59e0b", "clock", 3,
             ["accountant", "manager"], ["accountant", "manager"]),
            ("Finance Controller Review", "PENDING_FIN_CTRL", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#f59e0b", "cash-stack", 4,
             ["finance_manager", "finance_director", "cfo"], ["finance_manager"]),
            ("CFO Approval", "PENDING_CFO", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#dc2626", "shield-check", 5,
             ["cfo"], ["cfo"]),
            ("Posted", "POSTED", WorkflowStatus.COMPLETED, False, True, False, "#10b981", "check-circle-fill", 6, [], []),
            ("Rejected", "REJECTED", WorkflowStatus.REJECTED, False, True, False, "#ef4444", "x-circle-fill", 7, [], []),
            ("Revision Required", "REVISION", WorkflowStatus.REVISION_REQUIRED, False, False, False, "#8b5cf6", "arrow-repeat", 8, [], []),
        ])

        # Transitions
        self._create_transitions(workflow.id, states, [
            # Submit
            ("DRAFT", "SUBMITTED", "Submit for Approval", WorkflowActionType.SUBMIT, "Submit", "primary", False, False, []),
            # Manager actions
            ("SUBMITTED", "PENDING_MGR", "Route to Manager", WorkflowActionType.SUBMIT, "Route", "info", False, False, ["accountant"]),
            ("PENDING_MGR", "PENDING_FIN_CTRL", "Manager Approve", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["accountant", "manager"]),
            ("PENDING_MGR", "REJECTED", "Manager Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["accountant", "manager"]),
            ("PENDING_MGR", "REVISION", "Request Revision", WorkflowActionType.REVISE, "Request Revision", "warning", True, False, ["accountant", "manager"]),
            # Finance Controller actions
            ("PENDING_FIN_CTRL", "POSTED", "Controller Approve (< $50k)", WorkflowActionType.APPROVE, "Approve & Post", "success", False, False, ["finance_manager"]),
            ("PENDING_FIN_CTRL", "PENDING_CFO", "Escalate to CFO (> $50k)", WorkflowActionType.APPROVE, "Escalate to CFO", "warning", False, False, ["finance_manager", "finance_director"]),
            ("PENDING_FIN_CTRL", "REJECTED", "Controller Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["finance_manager", "finance_director"]),
            ("PENDING_FIN_CTRL", "REVISION", "Request Revision", WorkflowActionType.REVISE, "Request Revision", "warning", True, False, ["finance_manager", "finance_director"]),
            # CFO actions
            ("PENDING_CFO", "POSTED", "CFO Approve", WorkflowActionType.APPROVE, "Approve & Post", "success", False, False, ["cfo"]),
            ("PENDING_CFO", "REJECTED", "CFO Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["cfo"]),
            # Revision actions
            ("REVISION", "SUBMITTED", "Resubmit", WorkflowActionType.SUBMIT, "Resubmit", "primary", False, False, []),
        ])

        return workflow

    # ==================== 2. VENDOR PAYMENT WORKFLOW ====================
    def _seed_vendor_payment_workflow(self) -> WorkflowDefinition:
        """
        Vendor Payment Approval Workflow

        IFRS: IAS 7 (Cash Flows), IFRS 9 (Financial Instruments)

        Flow: Draft -> Payment Scheduled -> Finance Review -> CFO (>$50k) -> Processed

        Critical Controls:
        - All payments require dual authorization
        - Payments > $50,000 require CFO
        - Payments > $250,000 require CEO
        - Payments to new vendors require additional verification
        """
        workflow = WorkflowDefinition(
            id=str(uuid.uuid4()),
            name="Vendor Payment Approval",
            code="VENDOR_PAYMENT_APPROVAL",
            module="procurement",
            description="Approval workflow for vendor/supplier payments. All payments require dual authorization. High-value payments require executive approval.",
            is_active=True,
            is_default=True,
            requires_approval=True,
            auto_submit=False,
            approval_threshold_amount=0,  # All payments require approval
            max_approval_levels=4
        )
        self.db.add(workflow)
        self.db.flush()

        # States
        states = self._create_states(workflow.id, [
            ("Draft", "DRAFT", WorkflowStatus.DRAFT, True, False, False, "#6b7280", "file-earmark", 1, [], []),
            ("Payment Scheduled", "SCHEDULED", WorkflowStatus.SUBMITTED, False, False, False, "#3b82f6", "calendar-check", 2, [], ["accountant"]),
            ("Pending Finance Review", "PENDING_FIN", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#f59e0b", "cash-coin", 3,
             ["accountant", "finance_manager"], ["accountant", "finance_manager"]),
            ("Pending CFO Approval", "PENDING_CFO", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#dc2626", "shield-exclamation", 4,
             ["cfo"], ["cfo"]),
            ("Pending CEO Approval", "PENDING_CEO", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#7c2d12", "building", 5,
             ["ceo"], ["ceo"]),
            ("Approved for Payment", "APPROVED", WorkflowStatus.APPROVED, False, False, False, "#10b981", "check-circle", 6, [], ["accountant"]),
            ("Processed", "PROCESSED", WorkflowStatus.COMPLETED, False, True, False, "#059669", "check-circle-fill", 7, [], []),
            ("Rejected", "REJECTED", WorkflowStatus.REJECTED, False, True, False, "#ef4444", "x-circle-fill", 8, [], []),
            ("On Hold", "ON_HOLD", WorkflowStatus.ON_HOLD, False, False, False, "#6366f1", "pause-circle", 9, [], []),
        ])

        # Transitions
        self._create_transitions(workflow.id, states, [
            # Schedule payment
            ("DRAFT", "SCHEDULED", "Schedule Payment", WorkflowActionType.SUBMIT, "Schedule", "primary", False, False, []),
            # Finance review
            ("SCHEDULED", "PENDING_FIN", "Submit for Finance Review", WorkflowActionType.SUBMIT, "Submit", "info", False, False, ["accountant"]),
            # Finance actions
            ("PENDING_FIN", "APPROVED", "Finance Approve (< $50k)", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["accountant", "finance_manager"]),
            ("PENDING_FIN", "PENDING_CFO", "Escalate to CFO ($50k-$250k)", WorkflowActionType.APPROVE, "Escalate to CFO", "warning", False, False, ["finance_manager"]),
            ("PENDING_FIN", "REJECTED", "Finance Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["accountant", "finance_manager"]),
            ("PENDING_FIN", "ON_HOLD", "Put on Hold", WorkflowActionType.HOLD, "Hold", "secondary", True, False, ["accountant", "finance_manager"]),
            # CFO actions
            ("PENDING_CFO", "APPROVED", "CFO Approve (< $250k)", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["cfo"]),
            ("PENDING_CFO", "PENDING_CEO", "Escalate to CEO (> $250k)", WorkflowActionType.APPROVE, "Escalate to CEO", "warning", False, False, ["cfo"]),
            ("PENDING_CFO", "REJECTED", "CFO Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["cfo"]),
            # CEO actions
            ("PENDING_CEO", "APPROVED", "CEO Approve", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["ceo"]),
            ("PENDING_CEO", "REJECTED", "CEO Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["ceo"]),
            # Process payment
            ("APPROVED", "PROCESSED", "Process Payment", WorkflowActionType.COMPLETE, "Process", "success", False, False, ["accountant", "finance_manager"]),
            # Resume from hold
            ("ON_HOLD", "PENDING_FIN", "Resume Review", WorkflowActionType.RESUME, "Resume", "primary", False, False, ["accountant", "finance_manager"]),
        ])

        return workflow

    # ==================== 3. SALES CREDIT NOTE WORKFLOW ====================
    def _seed_sales_credit_note_workflow(self) -> WorkflowDefinition:
        """
        Sales Credit Note Approval Workflow

        IFRS: IFRS 15 - Revenue from Contracts with Customers (Variable Consideration)

        Flow: Draft -> Submitted -> Manager -> Finance -> CFO (>$25k) -> Posted

        Critical Controls:
        - All credit notes require approval (revenue reduction risk)
        - Credit > $5,000 requires Finance Manager
        - Credit > $25,000 requires CFO
        - Full invoice reversal requires CFO approval
        """
        workflow = WorkflowDefinition(
            id=str(uuid.uuid4()),
            name="Sales Credit Note Approval",
            code="SALES_CREDIT_NOTE_APPROVAL",
            module="sales",
            description="Approval workflow for sales credit notes. ALL credit notes require approval due to revenue reduction risk. High-value credits require executive approval.",
            is_active=True,
            is_default=True,
            requires_approval=True,
            auto_submit=False,
            approval_threshold_amount=0,  # All credit notes require approval
            max_approval_levels=4
        )
        self.db.add(workflow)
        self.db.flush()

        # States
        states = self._create_states(workflow.id, [
            ("Draft", "DRAFT", WorkflowStatus.DRAFT, True, False, False, "#6b7280", "file-earmark", 1, [], []),
            ("Submitted", "SUBMITTED", WorkflowStatus.SUBMITTED, False, False, False, "#3b82f6", "send", 2, [], ["manager"]),
            ("Pending Sales Manager", "PENDING_SALES_MGR", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#f59e0b", "person-check", 3,
             ["manager"], ["manager"]),
            ("Pending Finance Approval", "PENDING_FIN", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#f59e0b", "cash-stack", 4,
             ["accountant", "finance_manager"], ["finance_manager"]),
            ("Pending CFO Approval", "PENDING_CFO", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#dc2626", "shield-check", 5,
             ["cfo"], ["cfo"]),
            ("Approved", "APPROVED", WorkflowStatus.APPROVED, False, False, False, "#10b981", "check-circle", 6, [], []),
            ("Posted", "POSTED", WorkflowStatus.COMPLETED, False, True, False, "#059669", "check-circle-fill", 7, [], []),
            ("Rejected", "REJECTED", WorkflowStatus.REJECTED, False, True, False, "#ef4444", "x-circle-fill", 8, [], []),
        ])

        # Transitions
        self._create_transitions(workflow.id, states, [
            # Submit
            ("DRAFT", "SUBMITTED", "Submit Credit Note", WorkflowActionType.SUBMIT, "Submit", "primary", True, False, []),  # Requires justification
            # Route to Sales Manager
            ("SUBMITTED", "PENDING_SALES_MGR", "Route to Sales Manager", WorkflowActionType.SUBMIT, "Route", "info", False, False, []),
            # Sales Manager actions
            ("PENDING_SALES_MGR", "PENDING_FIN", "Sales Manager Approve", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["manager"]),
            ("PENDING_SALES_MGR", "REJECTED", "Sales Manager Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["manager"]),
            # Finance actions
            ("PENDING_FIN", "APPROVED", "Finance Approve (< $5k)", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["accountant", "finance_manager"]),
            ("PENDING_FIN", "PENDING_CFO", "Escalate to CFO (> $5k or Full Reversal)", WorkflowActionType.APPROVE, "Escalate", "warning", False, False, ["finance_manager"]),
            ("PENDING_FIN", "REJECTED", "Finance Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["accountant", "finance_manager"]),
            # CFO actions
            ("PENDING_CFO", "APPROVED", "CFO Approve", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["cfo"]),
            ("PENDING_CFO", "REJECTED", "CFO Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["cfo"]),
            # Post credit note
            ("APPROVED", "POSTED", "Post Credit Note", WorkflowActionType.COMPLETE, "Post", "success", False, False, ["accountant", "finance_manager"]),
        ])

        return workflow

    # ==================== 4. BAD DEBT WRITE-OFF WORKFLOW ====================
    def _seed_bad_debt_writeoff_workflow(self) -> WorkflowDefinition:
        """
        Bad Debt Write-off Approval Workflow

        IFRS: IFRS 9 - Financial Instruments (Impairment)

        Flow: Identified -> Credit Review -> Finance -> CFO -> Board (if material) -> Written Off

        Critical Controls:
        - All write-offs require documented collection efforts
        - Write-off > $10,000 requires Finance Director
        - Write-off > $50,000 requires CFO
        - Write-off > $100,000 requires Board notification
        """
        workflow = WorkflowDefinition(
            id=str(uuid.uuid4()),
            name="Bad Debt Write-off Approval",
            code="BAD_DEBT_WRITEOFF_APPROVAL",
            module="accounting",
            description="Approval workflow for bad debt write-offs. Requires documented collection efforts and proper authorization based on materiality thresholds. IFRS 9 compliant.",
            is_active=True,
            is_default=True,
            requires_approval=True,
            auto_submit=False,
            approval_threshold_amount=0,
            max_approval_levels=5
        )
        self.db.add(workflow)
        self.db.flush()

        # States
        states = self._create_states(workflow.id, [
            ("Identified", "IDENTIFIED", WorkflowStatus.DRAFT, True, False, False, "#6b7280", "exclamation-triangle", 1, [], []),
            ("Credit Review", "CREDIT_REVIEW", WorkflowStatus.SUBMITTED, False, False, True, "#3b82f6", "search", 2,
             ["credit_controller", "accountant"], ["credit_controller"]),
            ("Pending Finance Approval", "PENDING_FIN", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#f59e0b", "cash-stack", 3,
             ["finance_manager", "finance_director"], ["finance_manager"]),
            ("Pending CFO Approval", "PENDING_CFO", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#dc2626", "shield-check", 4,
             ["cfo"], ["cfo"]),
            ("Pending Board Review", "PENDING_BOARD", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#7c2d12", "people", 5,
             ["ceo"], ["ceo"]),  # CEO acts as board representative
            ("Approved", "APPROVED", WorkflowStatus.APPROVED, False, False, False, "#10b981", "check-circle", 6, [], []),
            ("Written Off", "WRITTEN_OFF", WorkflowStatus.COMPLETED, False, True, False, "#059669", "check-circle-fill", 7, [], []),
            ("Rejected", "REJECTED", WorkflowStatus.REJECTED, False, True, False, "#ef4444", "x-circle-fill", 8, [], []),
        ])

        # Transitions
        self._create_transitions(workflow.id, states, [
            # Submit for credit review
            ("IDENTIFIED", "CREDIT_REVIEW", "Submit for Credit Review", WorkflowActionType.SUBMIT, "Submit", "primary", True, True, []),  # Requires comment and attachment
            # Credit controller actions
            ("CREDIT_REVIEW", "PENDING_FIN", "Credit Review Complete", WorkflowActionType.APPROVE, "Send to Finance", "info", True, True, ["credit_controller", "accountant"]),
            ("CREDIT_REVIEW", "REJECTED", "Insufficient Documentation", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["credit_controller"]),
            # Finance actions
            ("PENDING_FIN", "APPROVED", "Finance Approve (< $10k)", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["finance_manager"]),
            ("PENDING_FIN", "PENDING_CFO", "Escalate to CFO ($10k-$50k)", WorkflowActionType.APPROVE, "Escalate", "warning", False, False, ["finance_manager", "finance_director"]),
            ("PENDING_FIN", "REJECTED", "Finance Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["finance_manager", "finance_director"]),
            # CFO actions
            ("PENDING_CFO", "APPROVED", "CFO Approve (< $100k)", WorkflowActionType.APPROVE, "Approve", "success", False, False, ["cfo"]),
            ("PENDING_CFO", "PENDING_BOARD", "Escalate to Board (> $100k)", WorkflowActionType.APPROVE, "Escalate to Board", "warning", False, False, ["cfo"]),
            ("PENDING_CFO", "REJECTED", "CFO Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["cfo"]),
            # Board actions (CEO as representative)
            ("PENDING_BOARD", "APPROVED", "Board Approve", WorkflowActionType.APPROVE, "Approve", "success", True, False, ["ceo"]),
            ("PENDING_BOARD", "REJECTED", "Board Reject", WorkflowActionType.REJECT, "Reject", "danger", True, False, ["ceo"]),
            # Process write-off
            ("APPROVED", "WRITTEN_OFF", "Process Write-off", WorkflowActionType.COMPLETE, "Write Off", "success", False, False, ["accountant", "finance_manager"]),
        ])

        return workflow

    # ==================== 5. PERIOD CLOSE WORKFLOW ====================
    def _seed_period_close_workflow(self) -> WorkflowDefinition:
        """
        Period Close Approval Workflow

        IFRS: IAS 1 - Presentation of Financial Statements

        Flow: Open -> Soft Close -> Reconciliation -> Review -> Hard Close

        Critical Controls:
        - Month-end close requires Finance Manager
        - Quarter-end close requires CFO
        - Year-end close requires CFO + External Audit
        - Reopen period requires CFO approval
        """
        workflow = WorkflowDefinition(
            id=str(uuid.uuid4()),
            name="Period Close Approval",
            code="PERIOD_CLOSE_APPROVAL",
            module="accounting",
            description="Approval workflow for accounting period close. Ensures proper review and authorization before finalizing financial periods. Month/Quarter/Year-end controls.",
            is_active=True,
            is_default=True,
            requires_approval=True,
            auto_submit=False,
            approval_threshold_amount=0,
            max_approval_levels=3
        )
        self.db.add(workflow)
        self.db.flush()

        # States
        states = self._create_states(workflow.id, [
            ("Period Open", "OPEN", WorkflowStatus.DRAFT, True, False, False, "#10b981", "unlock", 1, [], []),
            ("Soft Close", "SOFT_CLOSE", WorkflowStatus.SUBMITTED, False, False, False, "#f59e0b", "lock", 2, [], ["accountant"]),
            ("Reconciliation", "RECONCILIATION", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#3b82f6", "list-check", 3,
             ["accountant"], ["accountant"]),
            ("Pending Finance Review", "PENDING_FIN_REVIEW", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#f59e0b", "eye", 4,
             ["finance_manager"], ["finance_manager"]),
            ("Pending CFO Review", "PENDING_CFO_REVIEW", WorkflowStatus.PENDING_APPROVAL, False, False, True, "#dc2626", "shield-check", 5,
             ["cfo"], ["cfo"]),
            ("Hard Close", "HARD_CLOSE", WorkflowStatus.COMPLETED, False, True, False, "#059669", "lock-fill", 6, [], []),
            ("Reopened", "REOPENED", WorkflowStatus.REVISION_REQUIRED, False, False, False, "#8b5cf6", "unlock-fill", 7, [], []),
        ])

        # Transitions
        self._create_transitions(workflow.id, states, [
            # Initiate soft close
            ("OPEN", "SOFT_CLOSE", "Initiate Soft Close", WorkflowActionType.SUBMIT, "Soft Close", "warning", False, False, ["accountant", "finance_manager"]),
            # Start reconciliation
            ("SOFT_CLOSE", "RECONCILIATION", "Start Reconciliation", WorkflowActionType.SUBMIT, "Reconcile", "info", False, False, ["accountant"]),
            # Complete reconciliation
            ("RECONCILIATION", "PENDING_FIN_REVIEW", "Complete Reconciliation", WorkflowActionType.APPROVE, "Submit for Review", "primary", True, False, ["accountant"]),
            ("RECONCILIATION", "SOFT_CLOSE", "Issues Found", WorkflowActionType.REVISE, "Return", "warning", True, False, ["accountant"]),
            # Finance Manager review
            ("PENDING_FIN_REVIEW", "PENDING_CFO_REVIEW", "Finance Manager Approve (Quarter/Year End)", WorkflowActionType.APPROVE, "Escalate to CFO", "warning", False, False, ["finance_manager"]),
            ("PENDING_FIN_REVIEW", "HARD_CLOSE", "Finance Manager Approve (Month End)", WorkflowActionType.APPROVE, "Close Period", "success", False, False, ["finance_manager"]),
            ("PENDING_FIN_REVIEW", "RECONCILIATION", "Return for Adjustment", WorkflowActionType.REVISE, "Return", "warning", True, False, ["finance_manager"]),
            # CFO review
            ("PENDING_CFO_REVIEW", "HARD_CLOSE", "CFO Approve", WorkflowActionType.APPROVE, "Close Period", "success", True, False, ["cfo"]),
            ("PENDING_CFO_REVIEW", "RECONCILIATION", "Return for Adjustment", WorkflowActionType.REVISE, "Return", "warning", True, False, ["cfo"]),
            # Reopen period (exceptional)
            ("HARD_CLOSE", "REOPENED", "Reopen Period", WorkflowActionType.REVISE, "Reopen", "danger", True, False, ["cfo"]),
            ("REOPENED", "SOFT_CLOSE", "Close Reopened Period", WorkflowActionType.SUBMIT, "Re-close", "warning", True, False, ["cfo"]),
        ])

        return workflow

    # ==================== HELPER METHODS ====================
    def _create_states(
        self,
        workflow_id: str,
        state_definitions: List[Tuple]
    ) -> Dict[str, WorkflowState]:
        """
        Create workflow states from definitions

        state_definitions: List of tuples:
        (name, code, status, is_initial, is_final, requires_approval, color, icon, order, allowed_roles, notified_roles)
        """
        states = {}
        for state_def in state_definitions:
            name, code, status, is_initial, is_final, requires_approval, color, icon, order, allowed_roles, notified_roles = state_def

            state = WorkflowState(
                id=str(uuid.uuid4()),
                workflow_definition_id=workflow_id,
                name=name,
                code=code,
                status=status,
                is_initial=is_initial,
                is_final=is_final,
                requires_approval=requires_approval,
                color=color,
                icon=icon,
                display_order=order,
                allowed_roles=self._get_role_ids(allowed_roles) if allowed_roles else None,
                notified_roles=self._get_role_ids(notified_roles) if notified_roles else None
            )
            self.db.add(state)
            states[code] = state

        self.db.flush()
        return states

    def _create_transitions(
        self,
        workflow_id: str,
        states: Dict[str, WorkflowState],
        transition_definitions: List[Tuple]
    ):
        """
        Create workflow transitions from definitions

        transition_definitions: List of tuples:
        (from_state_code, to_state_code, name, action, button_label, button_color, requires_comment, requires_attachment, allowed_roles)
        """
        order = 1
        for trans_def in transition_definitions:
            from_code, to_code, name, action, button_label, button_color, requires_comment, requires_attachment, allowed_roles = trans_def

            if from_code not in states or to_code not in states:
                continue

            transition = WorkflowTransition(
                id=str(uuid.uuid4()),
                workflow_definition_id=workflow_id,
                from_state_id=states[from_code].id,
                to_state_id=states[to_code].id,
                name=name,
                action=action,
                button_label=button_label,
                button_color=button_color,
                requires_comment=requires_comment,
                requires_attachment=requires_attachment,
                allowed_roles=self._get_role_ids(allowed_roles) if allowed_roles else None,
                notify_on_transition=True,
                display_order=order
            )
            self.db.add(transition)
            order += 1

        self.db.flush()


def seed_phase1_workflows(db: Session) -> Dict[str, WorkflowDefinition]:
    """
    Main function to seed Phase 1 workflows

    Usage:
        from app.database.seed_workflows import seed_phase1_workflows
        from app.core.database import SessionLocal

        db = SessionLocal()
        workflows = seed_phase1_workflows(db)
        db.close()
    """
    seeder = WorkflowSeeder(db)
    return seeder.seed_all_phase1()


if __name__ == "__main__":
    # Allow running directly
    from app.core.database import SessionLocal

    db = SessionLocal()
    try:
        print("Seeding Phase 1 Workflows...")
        workflows = seed_phase1_workflows(db)
        print(f"Successfully created {len(workflows)} workflows:")
        for name, workflow in workflows.items():
            print(f"  - {workflow.name} ({workflow.code})")
        print("Done!")
    finally:
        db.close()
