#!/usr/bin/env python3
"""
Migration: Add IFRS tags to accounting_dimension_assignments

This script adds two new columns to track IFRS classification alongside dimension assignments:
- ifrs_reporting_tag: The IFRS tag from the accounting code (e.g., 'A1.1', 'L1.1')
- ifrs_category: Human-readable IFRS category (e.g., 'Current Assets')

These columns are auto-populated when dimensions are assigned through DimensionResolverService.
"""

import sys
from sqlalchemy import text
from app.core.database import engine


def run_migration():
    """Add IFRS columns to accounting_dimension_assignments table"""

    try:
        with engine.connect() as conn:
            print("Adding ifrs_reporting_tag column...")
            conn.execute(text("""
                ALTER TABLE accounting_dimension_assignments
                ADD COLUMN IF NOT EXISTS ifrs_reporting_tag VARCHAR(50) NULL
                COMMENT 'IFRS reporting tag from the journal entry'\''s accounting code'
            """))
            conn.commit()
            print("✓ Added ifrs_reporting_tag column")

            print("Adding ifrs_category column...")
            conn.execute(text("""
                ALTER TABLE accounting_dimension_assignments
                ADD COLUMN IF NOT EXISTS ifrs_category VARCHAR(100) NULL
                COMMENT 'Human-readable IFRS category description'
            """))
            conn.commit()
            print("✓ Added ifrs_category column")

            print("\nCreating index for ifrs_reporting_tag...")
            conn.execute(text("""
                CREATE INDEX IF NOT EXISTS idx_assignment_ifrs_tag
                ON accounting_dimension_assignments(ifrs_reporting_tag)
            """))
            conn.commit()
            print("✓ Created index for ifrs_reporting_tag")

            print("\nMigration completed successfully!")
            print("\nNew columns:")
            print("  - ifrs_reporting_tag: Stores IFRS tag (A1.1, L1.1, etc.)")
            print("  - ifrs_category: Stores category name (Current Assets, etc.)")
            print("\nThese are auto-populated by DimensionResolverService.apply_to_entry()")

    except Exception as e:
        print(f"✗ Migration failed: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    run_migration()
